how to make a binary search algorithm in c++ code example
Example 1: how to do binary search in c++ using STL
#include<bits/stdc++.h>
usind namespace std;
int main()
{
int arr[]={10,2,34,2,5,4,1};
sort(arr,arr+7);
binary_search(arr,arr+7,10);
binary_search(arr,arr+7,3);
return 0;
}
Example 2: c++ binary search
int result = -1;
int low = 0;
int high = N-1;
while (low <= high)
{ mid = (low + high) / 2;
if ( item == vector[mid])
{ result = mid;
break;
}
else if (item > vector[mid] )
{ low = mid + 1; }
else { high = mid - 1; }
}