-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.cpp
More file actions
44 lines (40 loc) · 863 Bytes
/
binarySearch.cpp
File metadata and controls
44 lines (40 loc) · 863 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
// iterative
// binary search
#include <iostream>
#include <vector>
using namespace std;
int binarySearch(vector<int>arr, int n, int ele) {
int l = 0, r = n-1;
while(l<=r) {
int mid = l + (r-l)/2;
if(arr[mid] == ele)
return mid;
if(arr[mid] > ele) {
r = mid-1;
}
else if(arr[mid] < ele) {
l = mid+1;
}
}
return -1;
}
int main()
{
vector<int> arr;
int n;
cout<<"enter the size of the array: ";
cin>>n;
cout<<"enter the elements in sorted order: ";
for(int i=0 ; i<n ; i++) {
int a;
cin>>a;
arr.push_back(a);
}
sort(arr.begin(), arr.end());
cout<<"Enter the element you want to search : ";
int ele;
cin>>ele;
int idx = binarySearch(arr,n,ele);
cout<<"\n"<<idx<<"\n";
return 0;
}