-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
52 lines (52 loc) · 1.16 KB
/
BinarySearch.cpp
File metadata and controls
52 lines (52 loc) · 1.16 KB
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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int search(vector<int> arr, int n, int key)
{
int s = 0;
int e = n - 1;
while (s <= e)
{
int mid = (s + e) / 2;
if (arr[mid] == key)
return mid;
else if (key > arr[mid])
s = mid + 1;
else
e = mid - 1;
}
return -1;
}
int main()
{
vector<int> arr;
int n, a, i, key;
cout << "Enter the size of the array: ";
cin >> n;
cout << "Enter the elements of the array: ";
for (i = 0; i < n; i++)
{
cin >> a;
arr.push_back(a);
}
sort(arr.begin(), arr.end());
cout << "Array in ascending order: ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
if (i == n - 1)
break;
}
cout << endl;
cout << "Enter the element to be searched: ";
cin >> key;
int ans = search(arr, n, key);
if (ans == -1)
cout << "The element is not present in the array." << endl;
else
cout << "The element is present at the position " << ans + 1 << endl;
return 0;
}
// Time Complexity=O(log n)
// Space Complexity=O(1)