summaryrefslogtreecommitdiff
path: root/algorithms/binary_search.cc
diff options
context:
space:
mode:
Diffstat (limited to 'algorithms/binary_search.cc')
-rw-r--r--algorithms/binary_search.cc27
1 files changed, 27 insertions, 0 deletions
diff --git a/algorithms/binary_search.cc b/algorithms/binary_search.cc
new file mode 100644
index 0000000..773fcf3
--- /dev/null
+++ b/algorithms/binary_search.cc
@@ -0,0 +1,27 @@
+#include <iostream>
+
+using namespace std;
+
+
+int binsearch(int* a, int val, int lo, int hi) {
+ if (hi < lo) return -1;
+ int mid = (lo+hi)/2;
+ if (val < a[mid]) {
+ return binsearch(a, val, lo, mid-1);
+ } else if (val > a[mid]) {
+ return binsearch(a, val, mid+1, hi);
+ } else {
+ return lo;
+ }
+}
+
+int main(void) {
+ int a[10] = {0,1,2,3,4,5,6,7,8,9};
+ int lo = 0;
+ int hi = 9;
+
+ int val = 3;
+
+ cout << binsearch(a, val, lo, hi) << endl;
+}
+