二分查找算法(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
相关文章推荐
- C++二分查找在搜索引擎多文档求交的应用分析
- C语言编程中实现二分查找的简单入门实例
- C#二分查找算法实例分析
- 二分查找算法在C/C++程序中的应用示例
- 在MySQL中实现二分查找的详细教程
- Java实现二分查找算法实例分析
- Python二分查找详解
- 简介二分查找算法与相关的Python实现示例
- 漫谈递归:二分查找算法的递归实现
- 二分查找
- [LeetCode] Find Minimum in Rotated Sorted Array
- 折半查找法
- "二分查找(Binary Search)"与"斐波那契查找(Fibonacci Search)"
- 二分查找
- C#版二分查找(代碼)
- 4495: Least Prime factor 找到最小质因子P的第N小正整数
- 使用Java完成《算法导论》习题2.3-5
- 使用Java完成《算法导论》习题2.3-6
- 使用Java完成《算法导论》习题2.3-7
- Sort Colors,Search in Rotated Sorted Array I,II,Merge Intervals,Insert Interval,Subsets II