Skip to content

Created BinarySearch cpp programme #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 3, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions BinarySearch.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
Time complexity: O(log n)
Contributor: Deepanshu Jindal(https://github.com/ultimatecoder2)
*/

#include<bits/stdc++.h>
using namespace std;

int BinarySearch(int arr[],int low,int high,int el)
{
if(low>high)
{
return -1;
}

int mid = (low+high)/2;
if(arr[mid] == el)
{
return mid;
}
if(arr[mid]<el)
{
return BinarySearch(arr,mid+1,high,el);
}
if(arr[mid]>el)
{
return BinarySearch(arr,low,mid-1,el);
}

}
int main()
{
int n;
cout<<"Enter Size of Array"<<endl;
cin>>n;
cout<<"Enter the elements of array"<<endl;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
cout<<"Enter the element that you want to find"<<endl;
int el;
cin>>el;
int index =BinarySearch(arr,0,n-1,el);
if(index<0)
cout<<"Element is not present in the array"<<endl;
else
{
cout<<"Element is present at "<<index + 1<<" position"<<endl;
}
return 0;
}