Write a recursive, boolean -valued method named search that accepts an integer a
ID: 3692087 • Letter: W
Question
Write a recursive, boolean -valued method named search that accepts an integer array , the number of elements in the array , and an integer (in that order), and returns whether the integer is present as an element in the array . Searching for a particular value in an array can be performed in the following recursive manner: •If the array has no elements , the value is not there. •Compare the first element of the array to the value , if they're equal , the value is there; other search for the value in the rest of the array .
Explanation / Answer
public class Search {
public static boolean search(int arr[], int key, int index){
//base case
if(arr == null || arr.length==0 || arr.length==index)
return false;
if(arr[index] == key)
return true;
//recursive case
return search(arr, key, index+1);
}
public static void main(String[] args) {
int arr[] = {2,4,5,67, 3,8,9,0,12,33445,5};
System.out.println(search(arr, 6, 0));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.