Given a sorted array of integers with possibly duplicates , how do you find an index isuch asA[i]=i
This is a problem in one of my books on programming (Cracking code interview). The solution is as follows:
public static int magicFast(int[] array, int start, int end) {
if (end < start || start < 0 || end >= array.length) {
return -1;
}
int midlndex = (start + end) / 2;
int midValue = array[midlndex];
if (midValue == midlndex) {
return midlndex;
}
int leftlndex = Math.min(midlndex - 1, midValue);
int left = magicFast(array, start, leftlndex);
if (left >= 0) {
return left;
}
int rightlndex = Math.max(midlndex + i, midValue);
int right = magicFast(array, rightlndex, end);
return right;
}
The author does not comment on the complexity of time. However, this is apparently a solution to O (n), since we need to look at both sides of the “midpoint”, in contrast to the problem in which the elements of the array are different. Recurrence ratio: T (n) = 2T (n / 2) + c (c is a constant time to check if the middle element is the answer)
How is it better than a simple linear scan? It is too complicated, just to achieve linear time efficiency. Did I miss something?