4-1 LC:二分查找
2020-08-31 本文已影响0人
Rumbles
有序数组的二分查找
NSInteger GetIndexInArr(NSArray *arr,NSNumber *num) {
NSInteger min = 0;
NSInteger max = arr.count - 1;
NSInteger mid = 0;
while (min <= max) {
mid = (min + max) / 2;
if ([arr[mid] integerValue] == num.integerValue) {
return mid;
} else if ([arr[mid] integerValue] > num.integerValue) {
max = mid - 1;
} else {
min = mid + 1;
}
}
return -1;
}