From 3cb3f429927ae76f7953d6f54844fb0fd4e6c8d5 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Mon, 8 Oct 2018 22:29:57 -0500 Subject: Binary search done! --- .../sources/binary_search.py | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 AlgoDesignAndTechniqueEdxPython/sources/binary_search.py (limited to 'AlgoDesignAndTechniqueEdxPython/sources') diff --git a/AlgoDesignAndTechniqueEdxPython/sources/binary_search.py b/AlgoDesignAndTechniqueEdxPython/sources/binary_search.py new file mode 100644 index 0000000..5f51289 --- /dev/null +++ b/AlgoDesignAndTechniqueEdxPython/sources/binary_search.py @@ -0,0 +1,27 @@ +# 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 binarySearch(a, key): + return binarySearchRecursive(a, 0, len(a) - 1, key) + +if __name__ == '__main__': + input = sys.stdin.read() + data = list(map(int, input.split())) + n = data[0] + 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