一、函数的调用
- (void)clicked {
NSArray *arrayNumbers = @[@-4,@-2,@4,@6,@9,@14,@23,@100];
NSInteger res = [self searchValue:arrayNumbers num:15];
NSInteger ress = [self searchValueIndex:arrayNumbers num:100 low:0 hight:[arrayNumbers count]];
NSLog(@"Chenfy--:%d",ress);
}
二、函数的实现
//迭代
- (NSInteger)searchValue:(NSArray *)arrayValue num:(NSInteger)num {
int low = 0,hight = [arrayValue count] - 1,mid;
while (!(low > hight)) {
mid = ((low + hight)/2);
NSInteger value = [arrayValue[mid] integerValue];
if (value == num) {
return mid;
}
if (value > num) {
hight = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
//递归
- (NSInteger)searchValueIndex:(NSArray *)arrayValue num:(NSInteger)num low:(NSInteger)low hight:(NSInteger)hight {
if (low > hight) {
return -1;
}
NSInteger mid = (low + hight)/2;
NSInteger value = [arrayValue[mid] integerValue];
if (value == num) {
return mid;
}
if (value > num) {
return [self searchValueIndex:arrayValue num:num low:low hight:mid - 1];
} else {
return [self searchValueIndex:arrayValue num:num low:mid + 1 hight:hight];
}
return -1;
}