Skip to content

Binary_Search in c++ #13

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

Open
wants to merge 1 commit into
base: master
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
43 changes: 43 additions & 0 deletions Binary-Search-c++/Binary Search.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int binarySearch(int *input,int beg,int end,int number){
if(beg>end){
return -1;
}
int mid = (beg+end)/2;
if(number == input[mid]){
return mid;
}
//Search left sub array
if(number<input[mid]){
return binarySearch(input,beg,mid-1,number);
}
//Search right sub array
else{
return binarySearch(input,mid+1,end,number);
}
}

int main(){
//Size of The Array
int n,number;
cin>>n;
// Create An array Of size n Dynamically
int *input = new int[n];
//Take Input Array in Ascending Order
for(int i=0;i<n;i++){
cin>>input[i];
}
//Take number to be searched
cin>>number;
//call the recursive function
int index = binarySearch(input,0,n-1,number);
if(index!=-1){
cout<<number<<" is found at index: "<<index<<endl;
}else{
cout<<number<<" not found"<<endl;
}
return 0;
}