-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
54 lines (47 loc) · 995 Bytes
/
Copy pathBinarySearch.cpp
File metadata and controls
54 lines (47 loc) · 995 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
elements should be in increasing
or decreasing order
*/
#include <iostream>
using namespace std;
int binarySearch(int key, int array[], int size) {
int start = 0;
int end = size - 1;
// int mid = (start + end) / 2;
int mid = start + (end - start) / 2;
/* int can take max upto 2^31-1 so to counter
mid not greater than this... */
while (start <= end) {
if (array[mid] == key) {
return mid;
} else if (key > array[mid]) {
start = mid + 1;
} else {
end = mid - 1;
}
mid = (start + end) / 2;
}
return -1;
}
/* complexity = logn */
/*
n
n/2
n/4
n/8
== n/2^k
n/2^k = 1
n = 2^k
k = log n
*/
// O(logn)
int main() {
int even[6] = {1, 2, 4, 7, 8, 10};
int odd[5] = {2, 3, 6, 8, 9};
int key;
cout << "Enter the elements to search: ";
cin >> key;
int index = binarySearch(key, odd, 6);
cout << "Element found at index: " << index << endl;
return 0;
}