Skip to content

Instantly share code, notes, and snippets.

@patelpreet422
Last active June 6, 2018 12:26
Show Gist options
  • Save patelpreet422/85fcd90f4d9d3839ed97bafe02123151 to your computer and use it in GitHub Desktop.
Save patelpreet422/85fcd90f4d9d3839ed97bafe02123151 to your computer and use it in GitHub Desktop.
Recursive binary search
#include <iostream>
#include <algorithm>
using namespace std;
bool binarySearchHelper(int key, int *array, int low, int high){
if(low == high) return array[low] == key;
if(low < high) {
int mid = (low + high)/2;
if(array[mid] == key) return true;
else if(array[mid] > key) return binarySearchHelper(key, array, low, mid);
else return binarySearchHelper(key, array, mid+1, high);
}
return false;
}
bool binarySearch(int key, int *array, int size){
return binarySearchHelper(key, array, 0, size-1);
}
int main()
{
int size = 4;
int key = 4;
int array[] = {1, 3, 5, 7};
cout << boolalpha << "key: " << key << ", " << binarySearch(key, array, size) << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment