I'm trying to implement binary search in Java. I'm working with an array of prime numbers up to 100. Here's the code:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
binarySearch(new int[]{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}, 29, 0, 24);
}
public static int binarySearch(int[] sortedArray, int key, int min, int max) {
int average = (min + max) / 2;
if (Arrays.asList(sortedArray).contains(key)) {
if (average == key) {
System.out.println("You have guessed the right number and it is: " + average);
return average;
} else if (key > average) {
System.out.println("Key is greater than average, going back to loop: " + average);
return binarySearch(sortedArray, key, average + 1, max);
} else {
System.out.println("Key is smaller than average, going back to loop : " + average);
return binarySearch(sortedArray, key, min, average - 1);
}
} else {
return -1;
}
}
I think that probably there's a problem with the call of binarySearch
in main
, but I'm not sure in what way I can implement it.
There are two main issues in your code (you could have easily figured them out if you ran the code with a debugger):
if (Arrays.asList(sortedArray).contains(key)) {
Why do you need this? The whole purpose of this method is to search for the key, so you shouldn't invoke this code. And besides, this code does not work because Arrays.asList(sortedArray)
would return a List<int[]>
, NOT a List<int>
, which will never contain the key, so this expression will always return false.
You're comparing the key to an index in the list, you should compare it against the element at the index:
if (sortedArray[average] == key) {
also
} else if (key > sortedArray[average]) {