Created
January 24, 2015 06:44
-
-
Save GurjotSinghMahi/36f1cbe19367512a1baf to your computer and use it in GitHub Desktop.
C++ Performing Binary search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Perform Binary search*/ | |
#include<iostream> | |
using namespace std; | |
int search(int arr[],int size,int item); | |
int main() | |
{ | |
int arr[20]; | |
int size; | |
int item; | |
cout<<"enter the number of elements you want to enter"<<endl; | |
cin>>size; | |
cout<<"enter the elements in array"<<endl; | |
for(int n=0;n<size;n++) | |
cin>>arr[n]; | |
cout<<"enter the element to be searched"<<endl; | |
cin>>item; | |
int location=search(arr,size,item); | |
if(location!=-1) | |
{ | |
cout<<"the element is present at "<<location+1<<" location"<<endl; | |
} | |
else | |
{ | |
cout<<"the element is not in the list"<<endl; | |
} | |
return 0; | |
} | |
int search(int arr[],int size,int item) | |
{ | |
int start=1; | |
int end=size; | |
while(start<=size) | |
{ | |
int mid=((start+end)/2); | |
if (arr[mid]==item) | |
{ | |
return mid; | |
} | |
if (arr[mid]>item) | |
{ | |
end=mid-1; | |
} | |
else | |
{ | |
start=mid+1; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment