From 6e042404f6123eb2afb60525b39aa6c21abd8bb6 Mon Sep 17 00:00:00 2001 From: whenofficial Date: Tue, 1 Oct 2019 21:22:50 +0800 Subject: [PATCH] binary search --- Algorithms/Search/binary_search.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Algorithms/Search/binary_search.py diff --git a/Algorithms/Search/binary_search.py b/Algorithms/Search/binary_search.py new file mode 100644 index 0000000..b19c38e --- /dev/null +++ b/Algorithms/Search/binary_search.py @@ -0,0 +1,27 @@ +""" +Binary Search Implementation using recursion +""" + +def binary_search(arr, x, y, z): + if y >= x: + mid = 1 + (y-1)//2 + + if arr[mid] == z: + return mid + elif arr[mid] > z: + return binary_search(arr, x, mid-1, z) + else: + return binary_search(arr, mid+1, y, z) + + else: + return -1 + + +# tests + +arr = [10, 20, 30, 100, 40, 200] +z = 100 + +ret = binary_search(arr, 0, len(arr)-1, z) +print(ret) +