-
Illustrate :
- Time Complexy :
O()=O(logn) - Advantage:
1、Less Compare frequency
2、Higher Speed
3、High-Efficiency - Disadvantage
1、Must be a Ordered Array
2、Operation like Delete、Update、Add is forbidden - OC code:
- (void)viewDidLoad {
[super viewDidLoad];
NSArray * tmpArr = @[@"1", @"12", @"123", @"1234", @"12345", @"123456", @"1234567", @"12345678", @"123456789", @"1234567890"];
NSLog(@"%ld", [self binarySearchKey:@"123" WithData:tmpArr]);
}
- (NSInteger)binarySearchKey:(NSString *)key WithData:(NSArray *)arr{
if (arr.count == 0) {
return -1;
}
NSInteger lowIndex = 0;
NSInteger highIndex = arr.count - 1;
while (lowIndex <= highIndex) {
NSInteger midIndex = lowIndex + (highIndex - lowIndex) / 2;
NSString * tmpStr = arr[midIndex];
if ([key isEqualToString:arr[midIndex]]) {
return midIndex;
}else if(key.length < tmpStr.length){
highIndex = midIndex + 1;
}else{
lowIndex = midIndex - 1;
}
}
return -1;
}