-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathbinarySearch.cpp
More file actions
43 lines (32 loc) · 809 Bytes
/
binarySearch.cpp
File metadata and controls
43 lines (32 loc) · 809 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
#include <iostream>
int binarySearch(int arr[], int left, int right, int x) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] < x) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int myarr[10];
int num;
int output;
std::cout << "Please enter 10 elements ASCENDING order" << std::endl;
for (int i = 0; i < 10; i++) {
std::cin >> myarr[i];
}
std::cout << "Please enter an element to search" << std::endl;
std::cin >> num;
output = binarySearch(myarr, 0, 9, num);
if (output == -1) {
std::cout << "No Match Found" << std::endl;
} else {
std::cout << "Match found at position: " << output << std::endl;
}
return 0;
}