Question: I was confronted not so long ago to an algorithmic problem.

I needed to find if a value stored in an array was at it "place".
An example will be easier to understand.

Let's take an Array A = {-10, -3, 3, 5, 7}. The algorithm would return 3, because the number 3 is at A[2] (3rd place).
On the contrary, if we take an Array B = {5, 7, 9, 10}, the algorithm will return 0 or false or whatever.

**The array is always sorted !**

I wasn't able to find a solution with a good complexity. (Looking at each value individualy is not good !) Maybe it is possible to resolve that problem by using an approach similar to merge sorting, by cuting in half and verifying on those halves ?

Can somebody help me on this one ? 
*Java algorithm would be the best, but pseudocode would also help me a lot !*

Answer: 
Here is an algorithm (based on binary search) to find all matching indices that has a best-case complexity of O(log(n)) and a worst case complexity of O(n):

1- Check the element at position m = array.length / 2

2- if the value array[m] is strictly smaller than m, you can forget about the left half of the array (from index 0 to index m-1), and apply recursively to the right half.

3- if array[m]==m, add one to the counter and apply recursively to both halves

4- if array[m]>m, forget about the right half of the array and apply recursively to the left half.

Using threads can accelerate things here. I suppose that there is no repetitions in the array.
If you want the find the first number in the array that is at its own place, you just have to iterate the array:

```
static int find_in_place(int[] a) {
    for (int i=0; i<a.length; i++) {
        if (a[i] == i+1) {
            return a[i];
        }
    }
    return 0;
}

```

It has a complexity of O(n), and an average cost of n/2