Skip to content

Commit 76ee36d

Browse files
authored
Merge pull request sat5297#39 from ultimatecoder2/master
Created BinarySearch cpp programme
2 parents a1c8112 + 21a4b4b commit 76ee36d

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

BinarySearch.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
Time complexity: O(log n)
3+
Contributor: Deepanshu Jindal(https://github.com/ultimatecoder2)
4+
*/
5+
6+
#include<bits/stdc++.h>
7+
using namespace std;
8+
9+
int BinarySearch(int arr[],int low,int high,int el)
10+
{
11+
if(low>high)
12+
{
13+
return -1;
14+
}
15+
16+
int mid = (low+high)/2;
17+
if(arr[mid] == el)
18+
{
19+
return mid;
20+
}
21+
if(arr[mid]<el)
22+
{
23+
return BinarySearch(arr,mid+1,high,el);
24+
}
25+
if(arr[mid]>el)
26+
{
27+
return BinarySearch(arr,low,mid-1,el);
28+
}
29+
30+
}
31+
int main()
32+
{
33+
int n;
34+
cout<<"Enter Size of Array"<<endl;
35+
cin>>n;
36+
cout<<"Enter the elements of array"<<endl;
37+
int arr[n];
38+
for(int i=0;i<n;i++)
39+
cin>>arr[i];
40+
cout<<"Enter the element that you want to find"<<endl;
41+
int el;
42+
cin>>el;
43+
int index =BinarySearch(arr,0,n-1,el);
44+
if(index<0)
45+
cout<<"Element is not present in the array"<<endl;
46+
else
47+
{
48+
cout<<"Element is present at "<<index + 1<<" position"<<endl;
49+
}
50+
return 0;
51+
}

0 commit comments

Comments
 (0)