一、二分法查找:适用于有序的列表查找想要的元素。
- 操作对象:数组
- 使用前提:有序的数组
- 性能方面:时间复杂度O(logn)
# -*- coding: utf-8 -*- def binary_search(list, item): low = 0 high = len(list) - 1 sequence = 0 while low <= high: mid = int((low + high) / 2) #这里必须是整数 guess = list[mid] sequence += 1 if guess == item: print('sequence', sequence) return mid if guess > item: high = mid - 1 else: low = mid + 1 return None list1 = range(129) list2 = range(10000009) print('index', binary_search(list1, 23)) print('index2', binary_search(list2, 2))
二、比较排序法:适用与数字之间的排序
2.1 选择排序:将数组元素按照从小到大的顺序排序,每次从数组中取出最小值
2.2、数组和链表
数组:连续存储在硬盘中;链表:分散存储在硬盘中;
def findsmallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selectionsort(arr): newarr = [] for i in range(len(arr)): smallest = findsmallest(arr) newarr.append(arr.pop(smallest)) return newarr print (selectionsort([1,2,3,2,2,2,234,3421,334,2343,443,52]))