通过二分法不断缩小查找范围,可更快定位元素位置。
思路:若是数组从小到大排序,拿中值与查找值比较,若是中值大,则查找值在左半边范围,若是中值小,则查找值在右半边范围。
intSearch(intarray[],intarray_size,intvalue){
intlow =0,high = array_size-1,mid;
while(low <= high) {
mid = (low+high)/2;
if(array[mid] == value) {
returnmid;
}
if(array[mid] > value) {
high = mid -1;
}else{
low = mid +1;
}
}
return-1;
}
- (NSInteger)searchValueWithArray:(NSArray*)array value:(NSNumber*)value{
NSArray *values = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSNumber*tNumber1 = (NSNumber*)obj1;
NSNumber*tNumber2 = (NSNumber*)obj2;
if([tNumber1integerValue] > [tNumber2integerValue]) {
return NSOrderedDescending;
}
if([tNumber1integerValue] < [tNumber2integerValue]) {
return NSOrderedAscending;
}
return NSOrderedDescending;
}];
NSLog(@"%@",values);
NSIntegerlow =0,high = [valuescount],mid;
while(low <= high) {
mid = (low + high)/2;
NSLog(@"%ld",mid);
if([values[mid]integerValue] == [valueintegerValue]) {
returnmid;
}
if([values[mid]integerValue] > [valueintegerValue]) {
high = mid -1;
}else{
low = mid +1;
}
}
return-1;
}