diff options
author | Patrick Simianer <p@simianer.de> | 2014-06-14 16:46:27 +0200 |
---|---|---|
committer | Patrick Simianer <p@simianer.de> | 2014-06-14 16:46:27 +0200 |
commit | 26c490f404731d053a6205719b6246502c07b449 (patch) | |
tree | 3aa721098f1251dfbf2249ecd2736434c13b1d48 /algorithms/binary_search.py |
init
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 ":-(" + + |