Created
May 8, 2013 06:24
-
-
Save happyrobots/5538613 to your computer and use it in GitHub Desktop.
An Objective-C BinarySearch category on Array of which members are String.
http://www.getappninja.com/blog/implementing-a-binary-search-in-ios
This file contains 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
@interface NSArray (BinarySearch) | |
// Before calling this method, make sure this array is an array of string and it is sorted using sortedArrayUsingSelector: | |
// NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; | |
- (unsigned long)indexOfStringUsingBinarySearch:(NSString *)searchString; | |
@end |
This file contains 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
#import "NSArray+BinarySearch.h" | |
@implementation NSArray (BinarySearch) | |
- (unsigned long)indexOfStringUsingBinarySearch:(NSString *)searchString { | |
NSString *member; | |
unsigned long mid; | |
unsigned long min = 0; | |
unsigned long max = [self count] - 1; | |
while (min <= max) { | |
mid = (min + max)/ 2; | |
member = [self objectAtIndex:mid]; | |
if ([searchString caseInsensitiveCompare:member] == NSOrderedSame) { | |
return mid; | |
} else if ([searchString caseInsensitiveCompare:member] == NSOrderedAscending) { | |
max = mid - 1; | |
} else { | |
min = mid + 1; | |
} | |
} | |
return NSNotFound; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment