diff options
Diffstat (limited to 'algorithms/binary_search.py')
-rwxr-xr-x | algorithms/binary_search.py | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/algorithms/binary_search.py b/algorithms/binary_search.py new file mode 100755 index 0000000..3d158dc --- /dev/null +++ b/algorithms/binary_search.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python2 + + +def bin_search(a, val, lo, hi): + print "%d %d"%(lo, hi) + if hi < lo: + return -1 + mid = (lo+hi)/2 + if a[mid] > val: + return bin_search(a, val, lo, mid-1) + elif a[mid] < val: + return bin_search(a, val, mid+1, hi) + else: + return mid + + +a = [1, 2, 3, 4, 5, 6, 7, 8] +# 0 1 2 3 4 5 6 7 + +if bin_search(a, 3, 0, len(a)-1): + print "Yay!" +else: + print ":-(" + + |