From 556c6e3637e04a9ca1e8b2b5687424d77e86b2f4 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Wed, 10 Oct 2018 19:50:37 -0500 Subject: Binary Search iterative approach done! Seems that recursive approach is better.--- .../sources/binary_search.py | 35 ++++++++++++++-------- 1 file 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 = ' ') -- cgit v1.2.3