algorithm binary search 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: binary search function in c++
#include<iostream>
using namespace std;
int binarySearch(int arr[], int p, int r, int num) {
if (p <= r) {
int mid = (p + r)/2;
if (arr[mid] == num)
return mid ;
if (arr[mid] > num)
return binarySearch(arr, p, mid-1, num);
if (arr[mid] > num)
return binarySearch(arr, mid+1, r, num);
}
return -1;
}
int main(void) {
int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int num = 33;
int index = binarySearch (arr, 0, n-1, num);
if(index == -1)
cout<< num <<" is not present in the array";
else
cout<< num <<" is present at index "<< index <<" in the array";
return 0;
}