The algorithm below is supposed to be a variation of the binary search where instead of picking the middle a random index is chosen and compared. The algorithm is asymptotically worse but it was just a task. The algorithm considers the case when the element at random index i is equal to the searching value in which case it returns true, and the second case when the element at index i is greater than the search value, in which case we recursively call the search on a input n of i - 1. And if the element is always greater than or equal to the searching value then the algorithm works fine.
However what happens when the element at randomized index is less than the search value? Intuitively I thought the input n should increase by i + 1 and even with checking if n becomes larger than the array size, I seem to be getting stackoverflows..
public static boolean search(int[] keys, int value, int n) {
if(n <= 0 || n > keys.length)
return false;
else {
Random random = new Random();
int i = random.nextInt(n);
if(keys[i] == value)
return true;
else if(keys[i] > value)
return search(keys, value, i - 1);
else
return search(keys, value, i + 1);
}
}
keys[]1-indexed? If not (and I feel it is not), change yourifcondition toif(n < 0 || n >= keys.length)1and value equals keys[0], then you are passing 0 to next recursive call. It will return false then. And if that is your assumption (for n), in any case, you are searching the lower part of the array from index 0 to (i-1) or (i+1) and never the second part. So, it is wrong there as well.Randomon every call of the method is bad practice. A singleRandominstance should be reused.