-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
56 lines (44 loc) · 925 Bytes
/
binary_search.cpp
File metadata and controls
56 lines (44 loc) · 925 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
55
56
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int key)
{
int found = 0;
int index = 0;
int middle;
int bottom = 0, top = n - 1;
do
{
middle = (top + bottom) / 2;
if (key == arr[middle])
found = 1;
else {
if (key < arr[middle])
top = middle - 1;
else
bottom = middle + 1;
}
} while (found == 0 && top >= bottom);
if (found == 0)
index = -1;
else
index = middle;
return index;
}
int main()
{
int n, key;
int arr[20];
cout << "Enter the size of the array" << endl;
cin >> n;
cout << "Enter sorted array" << endl;
for (int i = 0; i < n; i++)
cin >> arr[i];
cout << "Enter an element to be searched" << endl;
cin >> key;
int result = binarySearch(arr, n, key);
if (result == -1)
cout << "Element NOT found!" << endl;
else
cout << "Element found at index " << result;
return 0;
}