forked from ZhaofeiDing/interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.h
37 lines (33 loc) · 712 Bytes
/
BinarySearch.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 二分查找(折半查找):对于已排序,若无序,需要先排序
// 非递归
int BinarySearch(vector<int> v, int value , int low, int high) {
if (v.size() <= 0) {
return -1;
}
while (low <= high) {
int mid = low + (high - low) / 2;
if (v[mid] == value) {
return mid;
}
else if (v[mid] > value) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
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);
}