forked from Andyy-18/CPP-BASICS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbs.cpp
More file actions
48 lines (42 loc) · 788 Bytes
/
bs.cpp
File metadata and controls
48 lines (42 loc) · 788 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<bits/stdc++.h>
using namespace std;
void bsearch(int a[],int n,int key)
{
sort(a,a+n);
int start,end,mid;
start = 0;
end = n-1;
bool found = false;
while(start<=end)
{
mid = (start+end)/2;
if(a[mid]==key)
{
found = true;
break;
}
else
if(a[mid]>key)
end = mid-1;
else
start = mid+1;
}
if(found)
cout<<key<<" found at index "<<mid<<endl;
else
cout<<key<<" not found\n";
}
int main()
{
int n,k,i;
cout<<"Enter the number of elements in the array:- ";
cin>>n;
int arr[n];
cout<<"Enter "<<n<<" elements\n";
for(i=0;i<n;++i)
cin>>arr[i];
cout<<"Enter the element to be searched:- ";
cin>>k;
bsearch(arr,n,k);
return 0;
}