Reputation: 53
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?
Upvotes: 0
Views: 712
Reputation: 76077
As Rohit points out, you are taking advantage of char
type being a numeral type.
You can declare your "list" as char[]
and it should fix it, or use number literals.
Upvotes: 0
Reputation: 2520
You added to the list characters values.
Toggle the single quotes like this and it should be fine
{1,2,4,5};
So in your given case you are storing ascii values of the chars "1", "2", "3" and "4"
Upvotes: 1
Reputation: 213311
You are storing characters in integer array: -
int [] list = {'1', '2','4','5'};
So, the values you obtained is the ASCII code for 1, 2, 4, 5
respectively. Due to this, your binarySearch
method would not be able to find the value 4
ever. As, it is not exactly there. Remove those single quotes around your values.
Secondly, you are not printing the return value
of binarySearch
method: -
binarySearch(list, 4);
should be: -
System.out.println(binarySearch(list, 4));
Upvotes: 4