-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
46 lines (43 loc) · 859 Bytes
/
Copy pathbinarysearch.cpp
File metadata and controls
46 lines (43 loc) · 859 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
#include <bits/stdc++.h>
using namespace std;
void binarySearch(int arr[], int n, int num)
{
int right = n - 1, left = 0, mid = 0;
int i = 0;
bool found = false;
while (left <= right)
{
mid = left + (right - left) / 2;
if (arr[mid] == num)
{
bool found = true;
cout << "element found at position: " << mid << "\n";
return;
}
else if (arr[mid] < num)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
if (found == false)
{
cout << "Element not found\n";
}
}
int main()
{
int n, num;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "Enter element to search\n";
cin >> num;
binarySearch(arr, n, num);
}