8.3 Magic Index: A magic index in an array A [e ... n -1] is defined to be an index such that A[ i] = i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A. Follow up: What if the values are not distinct?
The idea: Use binary search to help guide us to the magic index. Consider, for example, the array
Say we land at index 3. Because all the elements are distinct, we know that A[i+1] > A[i]. Because the index 3 is greater than in the value at 3, which is 1, we know that the value has to catch up so it must exist in the right part of the array. The opposite is true for the left side.
We can show that if we have distinct elements, then our algorithm could fail. For example below, algorithm would search right when reach observing that A[4] < 4, when this is not the case.
0 1 2 3 4 5 6 7 8
-10,-5,2,2,2,2,2,2, 9
With this example, we can easily should the searching left or searching right are valid options.
So to formulate the upper bound on the left hand side: