Reputation: 1
JAVA Homework
Can someone give me some pointers on what I am doing wrong here? Thanks.
16.Code a recursive solution for Exercise 11(f), Binary search of an array to locate the value a Key.
public class BinarySearch {
public static void main(String[] args) {
public static int BinarySearch(int[] sorted, int first, int upto, int key) {
if (first < upto) {
int mid = first + (upto - first) / 2; // Compute mid point.
if (key < sorted[mid]) {
return BinarySearch(sorted, first, mid, key);
} else if (key > sorted[mid]) {
return BinarySearch(sorted, mid+1, upto , key);
} else {
return mid; // Found it.
}
}
return -(first + 1); // Failed to find key
}
}
}
Upvotes: 0
Views: 61
Reputation: 85779
The problem is that you're defining a method inside another method:
public static void main(String[] args) {
public static int BinarySearch(int[] sorted, int first, int upto, int key) {
Just move the BinarySearch
method outside the main
method:
public static void main(String[] args) {
//content of this method
}
public static int BinarySearch(int[] sorted, int first, int upto, int key) {
//content of this other method
}
Upvotes: 2