Python 常用排序
阿新 • • 發佈:2018-12-10
經典排序演算法:
def selecton_sort(p): """ 選擇排序 """ for i in range(len(p) - 1): min = i for j in range(i + 1, len(p)): if p[min] > p[j]: min = j if min != i: p[min], p[i] = p[i], p[min] return p def dubble_sort(p): """ 氣泡排序 """ for i in range(len(p)): for j in range(i + 1, len(p)): if p[i] > p[j]: p[i], p[j] = p[j], p[i] return p def insertion_sort(p): """ 插入排序 """ for i in range(1, len(p)): j = i while j > 0 and a[j - 1] > a[i]: j -= 1 p.insert(j, p[i]) p.pop(i + 1) return p # 快速排序 def sub_sort(array, low, high): key = array[low] while low < high: while low < high and array[high] >= key: high -= 1 while low < high and array[high] < key: array[low] = array[high] low += 1 array[high] = array[low] array[low] = key return low def quick_sort(array, low, high): if low < high: key_index = sub_sort(array, low, high) quick_sort(array, low, key_index) quick_sort(array, key_index + 1, high)
磁碟檔案排序:
from collections import defaultdict def mysort(): """ 大量資料排序: 比如你有100GB的資料需要排序,一次性載入到記憶體是不行的。 """ # 排序磁碟檔案,比如磁碟有100000個檔案, # 每個檔案由100個 1--10000 範圍內的數字組成 counter = defaultdict(int) for i in range(1, 100000): for n in open(f'{i}.txt', 'r'): counter[int(n)] += 1 with open('sort.txt', 'w') as f: for i in range(1, 10001): count = counter[i] if count: f.write(f'{i}\n' * count)