CODE
#include<iostream>
using namespace std;
int binary_search(int arr[], int size, int element)
{
int low,mid,high;
low=0;
high=size-1;
//start searching
while (low<=high)
{
mid=(low+high)/2;
if(arr[mid]==element)
{
cout<<"\nThe element "<<element<<" is found at position "<<mid+1;
break;
}
if (arr[mid]<element)
{
low=mid+1;
}
else{
high=mid-1;
}
}
if(low>high)
{
cout<<"element not found"<<endl;
}
}
int main()
{
//sorted array
int arr[10]={1,2,34,55,78,90,124,444,666,776};
int size=10;
int element;
cout<<"\nEnter the element do you want to search"<<endl;
cin>>element;
binary_search(arr,size,element);
return 0;
}
Output:
Enter the element do you want to search
34
The element 34 is found at position 3
0 Comments