mirror of
https://github.com/huihut/interview.git
synced 2024-03-22 13:10:48 +08:00
Merge pull request #50 from shoaibrayeen/patch-1
Converting BS in Standard Form
This commit is contained in:
commit
69d735735d
|
@ -1,22 +1,22 @@
|
||||||
// 二分查找(折半查找):对于已排序,若无序,需要先排序
|
// 二分查找(折半查找):对于已排序,若无序,需要先排序
|
||||||
|
|
||||||
// 非递归
|
// 非递归
|
||||||
int BinarySearch(vector<int> v, int value)
|
|
||||||
{
|
|
||||||
if (v.size() <= 0)
|
|
||||||
return -1;
|
|
||||||
|
|
||||||
int low = 0;
|
int BinarySearch(vector<int> v, int value , int low, int high) {
|
||||||
int high = v.size() - 1;
|
if (v.size() <= 0) {
|
||||||
while (low <= high)
|
return -1;
|
||||||
{
|
}
|
||||||
|
while (low <= high) {
|
||||||
int mid = low + (high - low) / 2;
|
int mid = low + (high - low) / 2;
|
||||||
if (v[mid] == value)
|
if (v[mid] == value) {
|
||||||
return mid;
|
return mid;
|
||||||
else if (v[mid] > value)
|
}
|
||||||
|
else if (v[mid] > value) {
|
||||||
high = mid - 1;
|
high = mid - 1;
|
||||||
else
|
}
|
||||||
|
else {
|
||||||
low = mid + 1;
|
low = mid + 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return -1;
|
return -1;
|
||||||
|
@ -34,4 +34,4 @@ int BinarySearch2(vector<int> v, int value, int low, int high)
|
||||||
return BinarySearch2(v, value, low, mid - 1);
|
return BinarySearch2(v, value, low, mid - 1);
|
||||||
else
|
else
|
||||||
return BinarySearch2(v, value, mid + 1, high);
|
return BinarySearch2(v, value, mid + 1, high);
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue
Block a user