1 import random 2 3 # 二分查找--递归实现 4 def binary_search(arr, left, right, num): 5 if left > right: 6 return -1 7 mid = (left + right) // 2 8 if arr[mid] < num: 9 left = mid + 1 10 elif arr[mid] > num: 11 right = mid - 1 12 else: 13 return mid 14 return binary_search(arr, left, right, num) 15 16 17 # 二分查找非递归实现 18 def binary_chop(arr, data): 19 n = len(arr) 20 first = 0 21 last = n - 1 22 23 while first <= last: 24 mid = (last + first) // 2 25 if arr[mid] > data: 26 last = mid - 1 27 elif arr[mid] < data: 28 first = mid + 1 29 else: 30 return mid 31 return -1 32 33 if __name__ == '__main__': 34 arr = [11, 32, 51, 21, 42, 9, 5, 6, 7, 8] 35 print(arr) 36 arr.sort() 37 print(arr) 38 39 num = random.randint(0, 52) 40 print('要查找的数:', num) 41 res = binary_search(arr, 0, len(arr) - 1, num) 42 if -1 == res: 43 print('未找到!') 44 else: 45 print('找到了,索引', res) 46 num = arr[random.randint(0, len(arr))] 47 print('要查找的数:', num) 48 res = binary_search(arr, 0, len(arr) - 1, num) 49 if -1 == res: 50 print('未找到!') 51 else: 52 print('找到了,索引', res) 53 54 print('*********************') 55 print('二分查找非递归实现') 56 num = random.randint(0, 52) 57 print('要查找的数:', num) 58 res = binary_search(arr, 0, len(arr) - 1, num) 59 if -1 == res: 60 print('未找到!') 61 else: 62 print('找到了,索引', res) 63 num = arr[random.randint(0, len(arr))] 64 print('要查找的数:', num) 65 res = binary_search(arr, 0, len(arr) - 1, num) 66 if -1 == res: 67 print('未找到!') 68 else: 69 print('找到了,索引', res)