您的位置:首页 > 其它

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

2016-03-25 17:29 597 查看
闲来无事,写写二分查找算法,如有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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二分查找