美文网首页iOS
Binary Search

Binary Search

作者: iCoder_木子弋 | 来源:发表于2018-01-09 10:51 被阅读3次
  • 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;
}

相关文章

网友评论

    本文标题:Binary Search

    本文链接:https://www.haomeiwen.com/subject/wdcinxtx.html