# -*- coding: utf-8 -*- def binary_search_rec(search_list, item): """二分查找, 递归""" lens = len(search_list) if lens > 0: mid = lens // 2 if search_list[mid] == item: return True elif search_list[mid] > item: return binary_search_rec(search_list[:mid], item) else: return binary_search_rec(search_list[mid+1:], item) return False def binary_search(search_list, item): """二分查找, 非递归""" lens = len(search_list) start = 0 end = lens-1 while start <= end: mid = (start + end) // 2 if search_list[mid] == item: return True elif search_list[mid] > item: end = mid - 1 else: start = mid + 1 return False def binary_search_firn(search_list, item): """二分查找, 查找第一个值等于给定值的元素""" lens = len(search_list) start = 0 end = lens-1 while start <= end: mid = (start + end) // 2 if search_list[mid] == item: if mid == 0 or search_list[mid-1] != item: return mid else: end = mid - 1 elif search_list[mid] > item: end = mid - 1 else: start = mid + 1 return False def binary_search_lastn(search_list, item): """二分查找, 查找最后一个值等于给定值的元素""" lens = len(search_list) start = 0 end = lens-1 while start <= end: mid = (start + end) // 2 if search_list[mid] == item: if mid == lens-1 or search_list[mid+1] != item: return mid else: start = mid + 1 elif search_list[mid] > item: end = mid - 1 else: start = mid + 1 return False def binary_search_fir(search_list, item): """二分查找, 查找第一个大于等于给定值的元素""" lens = len(search_list) start = 0 end = lens-1 while start <= end: mid = (start + end) // 2 if search_list[mid] >= item: if mid == 0 or search_list[mid-1] < item: return mid end = mid - 1 else: start = mid + 1 return False def binary_search_last(search_list, item): """二分查找, 查找最后一个小于等于给定值的元素 """ lens = len(search_list) start = 0 end = lens-1 while start <= end: mid = (start + end) // 2 if search_list[mid] <= item: if mid == lens - 1 or search_list[mid+1] > item: return mid start = mid + 1 else: end = mid - 1 return False if __name__ == '__main__': li = [2, 5, 9, 11, 20, 26, 29, 32, 38, 41, 47] print(binary_search(li, 30)) # false print(binary_search(li, 29)) # ture print(binary_search_rec(li, 2)) # ture print(binary_search_rec(li, 10)) # false li1 = [2, 5, 5, 11, 20, 20, 20, 32, 38, 41, 47] print(binary_search(li1, 20)) # 5 print(binary_search_firn(li1, 20)) # 4 print(binary_search_lastn(li1, 20)) # 6 print(binary_search_fir(li1, 1)) # 0 print(binary_search_fir(li1, 21)) # 7 print(binary_search_fir(li1, 40)) # 9 print(binary_search_last(li1, 3)) # 0 print(binary_search_last(li1, 12)) # 3 print(binary_search_last(li1, 48)) # 10
python实现二分查找和四种变形
最新推荐文章于 2024-08-15 09:03:12 发布