Binary Search

  • Illustrate :


    BinarySearch
  • 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;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容