Created
August 20, 2013 18:09
-
-
Save lonelytango/6285040 to your computer and use it in GitHub Desktop.
Binary Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSInteger)binarySearch:(id)object inArray:(NSArray *)array { | |
NSInteger minIndex = 0; | |
NSInteger maxIndex = [array count] - 1; | |
while (maxIndex >= minIndex) { | |
NSInteger midIndex = (maxIndex + minIndex) / 2; | |
if ([array[midIndex] compare:object] == NSOrderedAscending) { | |
minIndex = midIndex + 1; | |
} else if ([array[midIndex] compare:object] == NSOrderedDescending) { | |
maxIndex = midIndex - 1; | |
} else { | |
return midIndex; | |
} | |
} | |
return NSNotFound; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment