
Puzzle: LgN algorithm for Index == Value - tim_sw
http://idiomatic-fu.appspot.com/puzzle/3002/view
======
dangoldin
Given that the list is sorted you can just modify the basic binary search to
do what your want. Choose the middle and then compare the index with the value
- depending on the relationship look to the left or right and repeat.

------
lsb
This is a binary sort. How is that interesting?

~~~
spaghetti
For those that like these puzzles there's tons at TopCoder.com, spoj.pl,
usaco, etc.

------
spaghetti
bool f(vector<int> v){

/* use 0-based indice*/ int lowerBound = 0; int upperBound = v.size() - 1;

while(1){

    
    
    		if(lowerBound == upperBound) return v[lowerBound] == lowerBound;
    		
    		int i = lowerBound + (upperBound - lowerBound) / 2;
    		
    		if(v[i] == i){
    			
    			return true;
    			
    		}else if(v[i] < i){
    			
    			lowerBound = i + 1;
    			
    		}else if(v[i] > i){
    			
    			upperBound = i - 1;
    			
    		}
    	}
    }

~~~
shrughes
Typo alert! You meant

    
    
        int i = lowerBound + (upperBound - lowerBound) / 2;

~~~
spaghetti
ok corrected. thanks.

