一种是递归的,一种是非递归的
int binarySeach(int a[],int low,int high,int findNum)
{
if(low>high) {
return-1;
}
int mid = (low + high) /2;
if(findNum > a[mid]) {
low = mid +1;
return binarySeach(a, low, high, findNum);
}else if(findNum < a[mid])
{
high = mid -1;
return binarySeach(a, low, high, findNum);
}else
{
return mid;
}
}
int binarySeach2(int a[],int low,int high,int findNum)
{
while(low<=high) {
int mid = (low + high) /2;
if(findNum > a[mid]) {
low = mid +1;
}else if(findNum < a[mid])
{
high = mid -1;
}else
{
return mid;
}
}
return -1;
}
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
int a[] = {1,3,4,6,8,10,12,13,14,18,22,25,28,30,33,37,42,55,76,88,199,211};
int result =binarySeach2(a,0,21,199);
NSLog(@"result=%d",result);
}