binary search in bits/stdc++.h code example
Example 1: binary_search in vector in c++
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool f(int x, int y){
return x>y;
}
int main() {
vector<int> A ={ 11,2,3,14 };
cout<<A[1]<<endl;
sort(A.begin(), A.end());
cout<<A[1]<<endl;
bool present = binary_search(A.begin(), A.end(), 3);
cout<<present<<endl;
present = binary_search(A.begin(), A.end(), 5);
cout<<present<<endl;
A.push_back(100);
present = binary_search(A.begin(), A.end(), 100);
cout<<present<<endl;
A.push_back(100);
A.push_back(100);
A.push_back(100);
A.push_back(121);
vector<int>::iterator it = lower_bound(A.begin(), A.end(), 100);
vector<int>::iterator it2 = upper_bound(A.begin(), A.end(), 100);
cout<<*it<<" "<<*it2<<endl;
cout<<it2-it<<endl;
sort(A.begin(), A.end(), f);
vector<int>::iterator it3;
for (it3 =A.begin(); it3!= A.end(); it3++){
cout<<*it3<<" ";
}
cout<<endl;
for(int x: A){
cout<<x<<" ";
}
cout<<endl;
for(int &x: A){
x++;
cout<<x<<" ";
}
cout<<endl;
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;
}