I was studying recursion problem
I was going to call it, but it shows like this
import java.util.Arrays;
public class BinarySearch {
public static int binarySearch(int [] list, int key){
int low = 0;
int high = list.length -1;
return binarySearch(list, key, low ,high);
}
public static int binarySearch(int [] list, int key, int low, int high){
if(low > high){
return (-low -1);}
int mid = (low + high) / 2;
if(key < list[mid])
return binarySearch(list, key, low, mid - 1);
else if(key == list[mid])
return mid;
else
return binarySearch(list, key, mid + 1, high);
}
public static void main (String [] args){
int [] list = {'1', '2','4','5'};
binarySearch(list, 4);
System.out.println(Arrays.toString(list));
}
}
output : [49, 50, 52, 53]
what should I do to make it correct?
You are storing characters in integer array: –
So, the values you obtained is the ASCII code for
1, 2, 4, 5respectively. Due to this, yourbinarySearchmethod would not be able to find the value4ever. As, it is not exactly there. Remove those single quotes around your values.Secondly, you are not printing the
return valueofbinarySearchmethod: –should be: –