The proposed algorithm should be a variation of the binary search, where instead of choosing the average, a random index is selected and compared. The algorithm is asymptotically worse, but it was just a task. The algorithm considers the case when an element with a random index i is equal to the search value, in this case it returns true, and the second case when an element with an index i is larger than the search value, in which case we recursively call the input search i i - 1 And if the element is always greater than or equal to the search value, the algorithm works fine.
However, what happens when a randomized index entry is less than the search value? Intuitively, I thought that the input n should increase by i + 1 and even check if n will be larger than the size of the array, I seem to get 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);
}
}
source
share