二分查找算法(OC版--非递归实现)

闲来无事,写写二分查找算法,如有bug,请指出

//
//  ViewController.m
//  BinarySearch
//
//  Created by bcc_cae on 16/3/25.
//  Copyright © 2016年 bcc_cae. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSArray *arr = @[@1,@3,@5,@7,@9,@10,@12];
    int result = [self BinarySearch:arr target:@13];
    NSLog(@"%d",result);
    
}

- (int)BinarySearch:(NSArray *)arr target:(int)target
{
    if (!arr.count) {
        return -1;
    }
    unsigned int  low = 0;
    unsigned int  high = arr.count - 1;
    
    while (low<=high) {
        unsigned int mid = low + ((high-low)>>1); //防止加法溢出
        int  num = [arr objectAtIndex:mid];
        if (target == num) {
            return low;
        }else if(num > target)
        {
            high = mid -1;
        }else{
            low = mid +1;
        }
    }
    return -1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end



你可能感兴趣的:(二分查找)