import sys sys.setrecursionlimit(10000000)###设置最大递归深度 ## 冒泡算法 # 时间复杂度:O(n^2) 空间复杂度:O(1) def bubble_sort(li): for i in range(len(li)-1): # i = 0 flag = False for j in range(len(li)-1-i): # j = 6 if li[j] > li[j+1]: # li[j] = li[2] = 3 > li[j+1]=li[3]=4 li[j], li[j+1] = li[j+1], li[j] flag = True if not flag: return ### 选择排序 ### 时间复杂度: O(n^2) 空间复杂度: O(1) def select_sort(li): for i in range(len(li)-1): minLoc = i for j in range(i+1, len(li)): if li[minLoc] > li[j]: li[minLoc], li[j] = li[j], li[minLoc] ### 插入排序 ### 时间复杂度: O(n^2) 空间复杂度: O(1) def insert_sort(li): for i in range(1, len(li)): tmp = li[i] j = i - 1 while j>=0 and li[j] > tmp: li[j+1] = li[j] j = j - 1 li[j+1] = tmp ### 快速排序 ### 时间复杂度: O(nlogn) def partition(li, left, right): ### O(n) tmp = li[left] while left < right: while left < right and li[left] <= tmp: left = left + 1 li[right] = li[left] while left < right and li[right] >= tmp: right = right - 1 li[left] = li[right] li[left] = tmp return left def quick_sort(li, left, right): if left < right: mid = partition(li, left, right) ### O(n) quick_sort(li, left, mid-1) ### O(logn) quick_sort(li, mid+1, right) ### O(logn) ### O(logn) import random, time li = [random.randint(1,1000) for i in range(100000)] # print(li) start = time.time() quick_sort(li, 0, len(li)-1) print('quick_sort: ', time.time() - start) li = [random.randint(1,1000) for i in range(100000)] start = time.time() bubble_sort(li) print('bubble_sort: ', time.time() - start) li = [random.randint(1,1000) for i in range(100000)] start = time.time() select_sort(li) print('select_sort: ', time.time() - start) li = [random.randint(1,1000) for i in range(100000)] start = time.time() insert_sort(li) print('insert_sort: ', time.time() - start) # print(li)