折半查找法也称为二分查找法。它的基本思想是,将n个元素分成个数大致相同的两半,取a[n/2]与欲查找的x作比较,如果x=a[n/2]则找到x,算法终止。如 果x<a[n/2],则我们只要在数组a的左半部继续搜索x(这里假设数组元素呈升序排列)。如果x>a[n/2],则我们只要在数组a的右 半部继续搜索x。
假设其数组长度为n,其算法复杂度为o(log(n))。
伪代码写一下:
findYou(startIndex,countIndex)
{
//计算出中间位置
mid = (startIndex + countIndex)/2;
if(startIndex > countIndex - 1)
{
return -1;
}
if(searchScaleArray[min] == searchKey)
{
return min;
}
else
{
if(searchScaleArray[min] < searchKey)
{
//递归
findYou(min + 1,countIndex);
}
else
{
//递归
findYou(startIndex,mid - 1);
}
}
}
oc 代码实现:
#import "ViewController.h"
@interface ViewController ()
{
NSInteger searchKey;
NSInteger searchCount;
}
@property (nonatomic, strong) NSMutableArray *findArray;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
searchKey = 0;
searchCount = 0;
//保证是有序的
_findArray = [NSMutableArray arrayWithObjects:@0,@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12, nil];
[self findYouWithStartIndex:0 countIndex:_findArray.count];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark - 折半查找
- (NSInteger) findYouWithStartIndex:(NSInteger) startIndex countIndex:(NSInteger) countIndex
{
//获取中间值
NSInteger mid = (startIndex + countIndex)/2;
searchCount ++;
NSLog(@"计算次数-------%ld",(long)searchCount);
if (startIndex > countIndex - 1)
{
NSLog(@"-----\\%d\\------",-1);
return -1;
}
if ([_findArray[mid] integerValue] == searchKey)
{
NSLog(@"-----%ld------",(long)mid);
return mid;
}
else
{
if ([_findArray[mid] integerValue] < searchKey)
{
return [self findYouWithStartIndex:mid + 1 countIndex:countIndex];
}
else
{
return [self findYouWithStartIndex:startIndex countIndex:mid - 1];
}
}
}
@end