-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
48 lines (40 loc) · 861 Bytes
/
binarysearch.cpp
File metadata and controls
48 lines (40 loc) · 861 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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void binarysearch(int x, vector<int> &arr)
{
int i = 0, j = arr.size() - 1;
while (i <= j)
{
int mid = i + (j - i) / 2;
if (arr[mid] == x)
{
cout << "Element found at index " << mid << endl;
return;
}
else if (arr[mid] < x)
i = mid + 1;
else
j = mid - 1;
}
cout << "Element not found" << endl;
}
int main()
{
int size;
cout << "Enter the size: ";
cin >> size;
vector<int> arr(size);
cout << "Enter the array elements: ";
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
sort(arr.begin(), arr.end());
int x;
cout << "Enter the element to search: ";
cin >> x;
binarysearch(x, arr);
return 0;
}