iOS

Binary Search

2018-01-09  本文已影响3人  iCoder_木子弋
- (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;
}
上一篇 下一篇

猜你喜欢

热点阅读