forked from rishabhgarg25699/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
34 lines (34 loc) · 723 Bytes
/
binarysearch.cpp
File metadata and controls
34 lines (34 loc) · 723 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
#include<iostream>
#include<conio.h>
using namespace std;
int binarysearch(int *a,int l,int r,int x)
{
int mid=(l+r)/2;
if(x<a[mid])
return binarysearch(a,l,mid-1,x);
if(x>a[mid])
return binarysearch(a,mid+1,r,x);
if(x==a[mid])
return mid;
return -1;
}
int main()
{
int ans,n,x;
cout<<"Enter the size of the array";
cin>>n;
cout<<"Enter the values in the array";
int t,a[n];
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"Enter the element you want to find"<<endl;
cin>>x;
ans=binarysearch(a,0,n-1,x);
if(ans==-1)
cout<<"Element not found"<<endl;
else
cout<<"Element found at "<<ans<<"position;
return 0;
}