Last active
June 6, 2018 12:26
-
-
Save patelpreet422/85fcd90f4d9d3839ed97bafe02123151 to your computer and use it in GitHub Desktop.
Recursive binary search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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