From 21eb0e1c2fa8b9de34d4c6b4d3dee8b42e11347d Mon Sep 17 00:00:00 2001 From: caiwang-Z <58072883+caiwang-Z@users.noreply.github.com> Date: Sun, 22 May 2022 19:12:06 +0200 Subject: [PATCH] Create binarySearch --- sortAlgorithm/binarySearch | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 sortAlgorithm/binarySearch diff --git a/sortAlgorithm/binarySearch b/sortAlgorithm/binarySearch new file mode 100644 index 0000000..fff28cf --- /dev/null +++ b/sortAlgorithm/binarySearch @@ -0,0 +1,35 @@ +# 返回 x 在 arr 中的索引,如果不存在返回 -1 +def binarySearch (arr, l, r, x): + + # 基本判断 + if r >= l: + + mid = int(l + (r - l)/2) + + # 元素整好的中间位置 + if arr[mid] == x: + return mid + + # 元素小于中间位置的元素,只需要再比较左边的元素 + elif arr[mid] > x: + return binarySearch(arr, l, mid-1, x) + + # 元素大于中间位置的元素,只需要再比较右边的元素 + else: + return binarySearch(arr, mid+1, r, x) + + else: + # 不存在 + return -1 + +# 测试数组 +arr = [ 2, 3, 4, 10, 40 ] +x = 10 + +# 函数调用 +result = binarySearch(arr, 0, len(arr)-1, x) + +if result != -1: + print ("元素在数组中的索引为 %d" % result ) +else: + print ("元素不在数组中")