#include<iostream>
using namespace std;
//非递归
int binarySearch(int *a, int len, int goal) {
int low = 0;
int high = len - 1;
while (low<=high){
int middle = low + (high - low) / 2;
if (a[middle] == goal)
return middle;
else if (a[middle] > goal){
high = middle - 1;
}
else{
low = middle + 1;
}
}
return -1;
}
//递归
int binarySearch(int *a, int low, int high, int goal){
if (low > high){
return -1;
}
int middle = low + (high - low) / 2;
if (a[middle] == goal){
return middle;
}
else if(a[middle] > goal){
return binarySearch(a, low, middle - 1, goal);
}
else{
return binarySearch(a, middle + 1, high, goal);
}
return -1;
}
二分查找
最新推荐文章于 2023-05-28 13:59:52 发布