binary serach cpp code example
Example 1: binary search program c++
#include <iostream>
using namespace std;
int binarySearch(int array[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
int main ()
{
const int size = 5;
int array[size] = {1, 2, 3, 4, 5};
int value;
int result;
cout << "What value would you like to search for? ";
cin >> value;
result = binarySearch(array, size, value);
if (result == -1)
cout << "Not found\n";
else
cout << "Your value is in the array.\n";
return 0;
}
Example 2: Binary search in c++
#include<iostream>
#include<cmath>
using namespace std;
int BinSearch( int arr[],int key,int len)
{
int h,mid,l;
l=0;
h=len-1;
while(l<=h)
{
mid=((l+h)/2);
if(key==arr[mid])
return mid;
else if(key<arr[mid])
h=mid-1;
else
l=mid+1;
}
return -1;
}
int main()
{
int key,i,len;
int arr[] = {1,2,3,6,9,12,15,34,54};
len=sizeof(arr)/sizeof(arr[0]);
cout<<"enter the key to be searched";
cin>>key;
int result= BinSearch(arr,key,len);
(result == -1)
? cout<<"Element is not present in the array"<<endl
: cout<<"Element is present at index : "<<result<<endl;
for(i=0;i<len-1;i++)
cout<<arr[i]<<" ";
return 0;
}