-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary-Search.cpp
More file actions
42 lines (33 loc) · 869 Bytes
/
Binary-Search.cpp
File metadata and controls
42 lines (33 loc) · 869 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
//Searches a number in an array using binary search technique
#include<iostream>
using namespace std;
int main() {
int n, i, arr[50], search, first, last, middle;
cout << "Enter total number of elements :";
cin >> n;
cout << "Enter "<< n << " numbers :";
for (i=0; i<n; i++) {
cin >> arr[i];
}
cout << "Enter a number to find :";
cin >> search;
first = 0;
last = n-1;
middle = (first+last)/2;
while (first <= last) {
if(arr[middle] < search) {
first = middle + 1;
}
else if(arr[middle] == search) {
cout << search << " found at location " << middle+1 << "\n";
break;
}
else {
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last) {
cout << "Not found! " << search << " is not present in the list.";
}
}