My teacher wrote an algorithm to find a number in an array. I have tried to convert it to find a char.
If I search for the the first char of an array it works, but if I try to find the last char in the same array it gives me 0 or an unexpected number (like 100+, when the array is like 4 chars).
Here's the code:
int myIndex = binarySearch(sentence , word[0], 0, sentence.length -1);
char [] sentence = {'s','t','a','c','k','o','v','e','r','f','l','o','w'};
char [] word = {'o','v','e','r'};
static int binarySearch(char [] arr, char x, int l, int r){
if(r<l){
return 0;
}
int m = l+(r-l)/2;
if(arr[m] == x){
return m;
}
if(arr[m] < x){
return binarySearch(arr, x, m+1, r);
}
return binarySearch(arr, x, l, m-1);
}
If I search for the first letter in the word array it works fine, but if I search for the last letter in the word array it breaks.