PLEASE, FOLLOW THE INSTRUCTIONS. I NEED YOUR CODE TO COMPILE AND PASS THE DRIVES
ID: 3539701 • Letter: P
Question
PLEASE, FOLLOW THE INSTRUCTIONS.
I NEED YOUR CODE TO COMPILE AND PASS THE DRIVESEARCH.
EXPLAIN YOUR CODE WITH COMMENTS USING //.
Thank You!
The value is equal to the middle element. In this case, the element has been found and you are done. Then, return its key.
The value is greater than the middle element, we will consider the right half sub-array of the array
The value is less than the middle element, we will take the left half of the array, before the middle element.
We will keep on repeating the above process with their sub-arrays, until we find the match.
If we can%u2019t find the value till the end of the process, it should return -1, which represents there's no such value in the array.
Notice, in the above enumeration, number 1 and 5 would the two base cases in the recursion.
Now, Write a program that implements Binary Search Recursively on Arrays .
Complete the following class "BinarySearch". Please read the comments carefully.
}
We will test your code with class DriverSearch and it should return following output. Remember to return -1, if there is no such element in the array.
} }
Output
2
-1
Also here is some code attached with the assignment if it helps:
Explanation / Answer
BinarySearch.java
.....................................................................
public class BinarySearch {
public static int search(int find, int [] array, int left, int right) {
if (left < right) {
int mid = (left + right+1) / 2; // Compute mid point.
/* If value to be searched is less than the array[mid] , then
the find value is searched from 0 to mid-1 value recursively */
if (find < array[mid]) {
return search(find, array, left, mid-1);
}
/* If value to be searched is greater than the array[mid] , then
the find value is searched from mid+1 to right value recursively */
else if (find > array[mid]) {
return search(find, array, mid+1 , right);
}
/* If value to be searched is equal to array[mid] , then
index of mid is returned */
else {
return mid; // Found it.
}
}
else if (left == right) {
if (find == array[left]) {
return left; // Element is found .
}
}
return -1; // Failed to find element and return -1
}
}
...........................................................................................
DriverSearch.java
......................................................
} }
.............................................................................................
Output
2
-1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.