-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_searc.cpp
56 lines (45 loc) · 1019 Bytes
/
Binary_searc.cpp
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
53
54
55
56
////////..........................
//................................RECURSIVE BINARY__SEARCH OPERATION
//..................................................................///////////////
#include<iostream>
#include<algorithm>
using namespace std;
int bin_srch(int a[],int x,int p,int r)
{
int q;
if(p==r)
{
if(x==a[p])
return p;
else
return -1;
}
else
{
q = (p+r)/2;
if(x> a[q])
return (bin_srch(a,x,q+1,r) );
else
return( bin_srch(a,x,p,q) );
}
}
int main()
{
int n,i,x,index;
cout<<"Enter size of array\n";
cin>>n;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<"Enter element you want to search\n";
cin>>x;
index = bin_srch(a,x,0,n-1);
if(index!=-1)
cout<<"Element found at index : "<<index;
else
cout<<"Element not present in given list \n";
return 0;
}