Skip to content
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

Iterative cpp template for binary search #17

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
36 changes: 36 additions & 0 deletions binarysearch.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include <bits/stdc++.h>
using namespace std;

bool binarysearch(vector<int>& arr, int elem){
int left=0;
sort(arr.begin(), arr.end()); //since binary search works only in sorted array
int right= arr.size()-1;
while(left<=right){
int pivot= left + (right-1)/2; //finding out the center element
if(arr[pivot]==elem)
return true;
if(arr[pivot]>elem) //if center element is greater than the element to search, the element must be in first half, so right changes to pivot-1
right=pivot-1;
else
left= pivot+1;
}
return false;
}

int main(){
vector<int> arr;
int n;
cin>>n; //size of array
int x=0;
for(int i=0;i<n;i++){
cin>>x;
arr.push_back(x);
}
int elem=0;
cin>>elem; //the element to search
bool ispresent= binarysearch(arr, elem);
if(ispresent)
cout<<"Element Found";
else
cout<<"Element not in array";
}