summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHaidong Ji2018-10-10 19:50:37 -0500
committerHaidong Ji2018-10-10 19:50:37 -0500
commit556c6e3637e04a9ca1e8b2b5687424d77e86b2f4 (patch)
tree385acce5b40508ec32f138832cbf1c26bd631a97
parent3cb3f429927ae76f7953d6f54844fb0fd4e6c8d5 (diff)
Binary Search iterative approach done!
Seems that recursive approach is better.
-rw-r--r--AlgoDesignAndTechniqueEdxPython/sources/binary_search.py35
1 files changed, 23 insertions, 12 deletions
diff --git a/AlgoDesignAndTechniqueEdxPython/sources/binary_search.py b/AlgoDesignAndTechniqueEdxPython/sources/binary_search.py
index 5f51289..21d3ad5 100644
--- a/AlgoDesignAndTechniqueEdxPython/sources/binary_search.py
+++ b/AlgoDesignAndTechniqueEdxPython/sources/binary_search.py
@@ -1,20 +1,32 @@
# Uses python3
import sys
-def binarySearchRecursive(a, low, high, key):
- if high < low:
- return -1
- mid = (int) (low + (high - low) / 2)
- if key == a[mid]:
- return mid
- elif key < a[mid]:
- return binarySearchRecursive(a, low, mid - 1, key)
- else:
- return binarySearchRecursive(a, mid + 1, high, key)
+# def binarySearchRecursive(a, low, high, key):
+# if high < low:
+# return -1
+# mid = (int) (low + (high - low) / 2)
+# if key == a[mid]:
+# return mid
+# elif key < a[mid]:
+# return binarySearchRecursive(a, low, mid - 1, key)
+# else:
+# return binarySearchRecursive(a, mid + 1, high, key)
+
+def binarySearchIterative(a, low, high, key):
+ while low <= high:
+ mid = (int) (low + (high - low)/2)
+ if key == a[mid]:
+ return mid;
+ elif key < a[mid]:
+ high = mid - 1
+ else:
+ low = mid + 1
+ return -1
def binarySearch(a, key):
- return binarySearchRecursive(a, 0, len(a) - 1, key)
+# return binarySearchRecursive(a, 0, len(a) - 1, key)
+ return binarySearchIterative(a, 0, len(a) - 1, key)
if __name__ == '__main__':
input = sys.stdin.read()
@@ -23,5 +35,4 @@ if __name__ == '__main__':
m = data[n + 1]
a = data[1 : n + 1]
for x in data[n + 2:]:
- # replace with the call to binary_search when implemented
print(binarySearch(a, x), end = ' ')