- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
Latest commit
25 lines (22 loc) · 648 Bytes
/
Copy pathbinary_search.cpp
File metadata and controls
25 lines (22 loc) · 648 Bytes
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
#include<iostream>
usingnamespacestd;
intbinary_search(int data[], int size, int key) {
int left = 0, right = size - 1, mid = (left + right) / 2;
while (left <= right) { // Caution: '<=' instead of '<'!
if (key > data[mid]) {
left = mid + 1;
mid = (left + right) / 2;
} elseif (key < data[mid]) {
right = mid - 1;
mid = (left + right) / 2;
} else {
return mid;
}
}
return -1;
}
intmain() {
int data[] = {2, 5, 8, 13, 52, 79, 159, 500, 687, 861, 901, 999, 1000};
cout << binary_search(data, 12, 5) << endl;
return0;
}