1 二分查找:二分查找从有序列表的候选区data[0:n]开始,通过对半查找的值与候选区中间的值进行比较
方法一:利用for循环, 时间复杂度是o(n)
li = [1, 3, 5, 7, 9, 11, 15, 18, 20] def linear_serach(li, value): for i in range(len(li)): if li[i] == value: return i return print(linear_serach(li,3))
方法二: 利用二分查找, 效率高, 时间复杂度: 0(logn)
li = [1, 3, 5, 7, 9, 11, 15, 18, 20] def bin_serach(li, value): low = 0 high = len(li) - 1 while low < high: mid = (low + high) // 2 if li[mid] > value: high = mid - 1 elif li[mid] < value: low = mid + 1 else: return mid print(bin_serach(li, 3)) # 时间复杂度: 0(logn)
2 冒泡排序:
原文地址:https://www.cnblogs.com/gyh412724/p/10181815.html
时间: 2024-11-04 13:43:11