News for hackers. Stuff that matters.
Re:Puzzle: LgN algorithm for Index == Value by dangoldin on Saturday April 11, 2009 @11:23PM (#558117)
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.
Re:Puzzle: LgN algorithm for Index == Value by lsb on Saturday April 11, 2009 @11:48PM (#558136)
This is a binary sort. How is that interesting?
Re:Puzzle: LgN algorithm for Index == Value by spaghetti on Saturday April 11, 2009 @11:56PM (#558143)
For those that like these puzzles there's tons at TopCoder.com, spoj.pl, usaco, etc.
Re:Puzzle: LgN algorithm for Index == Value by spaghetti on Saturday April 11, 2009 @11:41PM (#558129)
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;
			
		}
	}
}
Re:Puzzle: LgN algorithm for Index == Value by shrughes on Saturday April 11, 2009 @11:58PM (#558145)
Typo alert! You meant

    int i = lowerBound + (upperBound - lowerBound) / 2;
Re:Puzzle: LgN algorithm for Index == Value by spaghetti on Sunday April 12, 2009 @12:14AM (#558163)
ok corrected. thanks.
Re:Puzzle: LgN algorithm for Index == Value by bf on Monday April 13, 2009 @02:04AM (#559469)
Your function crashes when passed an empty vector. Defensive programming please! :-)
Re:Puzzle: LgN algorithm for Index == Value by spaghetti on Monday April 13, 2009 @11:30PM (#560944)
good point. add

    if(v.size() == 0) return false;
Re:Puzzle: LgN algorithm for Index == Value by bf on Monday April 13, 2009 @02:07AM (#559475)
And don't get me started with passing by value! Okay, I'll stop being a dick.