defselection_sort(list): n=len(list) for i inrange (0,n): min = i for j inrange(i+1,n): iflist[j]<list[min]: min=j list[min],list[i]=list[i],list[min] returnlist
defshell_sort(list): n = len(list) # 初始步长 gap = n // 2 while gap > 0: for i inrange(gap, n): # 每个步长进行插入排序 temp = list[i] j = i # 插入排序 while j >= gap andlist[j - gap] > temp: list[j] = list[j - gap] j -= gap list[j] = temp # 得到新的步长 gap = gap // 2 returnlist
defquick_sort(list): less = [] pivotList = [] more = [] # 递归出口 iflen(list) <= 1: returnlist else: # 将第一个值做为基准 pivot = list[0] for i inlist: # 将比急转小的值放到less数列 if i < pivot: less.append(i) # 将比基准打的值放到more数列 elif i > pivot: more.append(i) # 将和基准相同的值保存在基准数列 else: pivotList.append(i) # 对less数列和more数列继续进行排序 less = quick_sort(less) more = quick_sort(more) return less + pivotList + more
分而治之的思想实现:
下面这段代码出自《算法图解》传说中的三行实现python快速排序。
1 2 3 4 5 6 7 8
defqsort(arr): iflen(arr) <= 1: return arr else: pivot = arr[0] less = [x for x in arr[1:] if x < pivot] greater = [x for x in arr[1:] if x >= pivot] return qsort(less) + [pivot] + qsort(greater)
一行语法糖版本:
1
qs = lambda xs : ( (len(xs) <= 1and [xs]) or [ qs( [x for x in xs[1:] if x < xs[0]] ) + [xs[0]] + qs( [x for x in xs[1:] if x >= xs[0]] ) ] )[0]
defcount_sort(list): min = 2147483647 max = 0 # 取得最大值和最小值 for x inlist: if x < min: min = x if x > max: max = x # 创建数组C count = [0] * (max - min +1) for index inlist: count[index - min] += 1 index = 0 # 填值 for a inrange(max - min+1): for c inrange(count[a]): list[index] = a + min index += 1 returnlist