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

added binary search iterative #164

Merged
merged 1 commit into from
Oct 19, 2019
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
56 changes: 56 additions & 0 deletions search/binary_search/binary_search_iterative.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include<iostream>
using namespace std;

int bin_search(int arr[],int low, int high, int x)
{
int mid;
while(low<=high)
{
mid = (low + high)/2;
if( arr[mid] == x)
{
return mid;
}
else if(x < arr[mid])
{
high = mid -1;
}
else
{
low = mid + 1;
}
}

return -99;
}
int main()
{
int *arr,i,j,n,item,flag;
cout<<"Enter the no. of elements:";
cin>>n;
cout<<"Enter the elements(in ascending order):\n";
arr=new int[n];
for(i=0;i<n;i++)
{
cout<<"["<<i<<"]:";
cin>>arr[i];
}
cout<<"original array:\n";
for(i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}

cout<<"\nEnter the element to be searched:";
cin>>item;

flag = bin_search(arr,0,n-1,item);
if(flag == -99)
{
cout<<"\nElement not found";
}
else
{
cout<<"\nElement found at "<<flag + 1<<" position!!!";
}
}