2018-03-10 17:45:53 +08:00
|
|
|
// 二分查找(折半查找):对于已排序,若无序,需要先排序
|
|
|
|
|
|
|
|
// 非递归
|
|
|
|
|
2019-09-06 16:16:39 +08:00
|
|
|
int BinarySearch(vector<int> v, int value , int low, int high) {
|
|
|
|
if (v.size() <= 0) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
while (low <= high) {
|
2018-03-10 17:45:53 +08:00
|
|
|
int mid = low + (high - low) / 2;
|
2019-09-06 16:16:39 +08:00
|
|
|
if (v[mid] == value) {
|
2018-03-10 17:45:53 +08:00
|
|
|
return mid;
|
2019-09-06 16:16:39 +08:00
|
|
|
}
|
|
|
|
else if (v[mid] > value) {
|
2018-03-10 17:45:53 +08:00
|
|
|
high = mid - 1;
|
2019-09-06 16:16:39 +08:00
|
|
|
}
|
|
|
|
else {
|
2018-03-10 17:45:53 +08:00
|
|
|
low = mid + 1;
|
2019-09-06 16:16:39 +08:00
|
|
|
}
|
2018-03-10 17:45:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
// 递归
|
|
|
|
int BinarySearch2(vector<int> v, int value, int low, int high)
|
|
|
|
{
|
|
|
|
if (low > high)
|
|
|
|
return -1;
|
|
|
|
int mid = low + (high - low) / 2;
|
|
|
|
if (v[mid] == value)
|
|
|
|
return mid;
|
|
|
|
else if (v[mid] > value)
|
|
|
|
return BinarySearch2(v, value, low, mid - 1);
|
|
|
|
else
|
|
|
|
return BinarySearch2(v, value, mid + 1, high);
|
2019-09-06 16:16:39 +08:00
|
|
|
}
|