首页 > 代码库 > Python 排序算法的实现

Python 排序算法的实现

冒泡排序:

1 def bubble(l):2     length = len(l)3     for i in range(length):4         for j in range(i+1, length):5             if l[i] > l[j]:6                 l[i], l[j] = l[j], l[i]7     print l

选择排序:

1 def select(l):2     length = len(l)3     for i in range(length):4         minn = i5         for j in range(i+1, length):6             if l[j] < l[minn]:7                 minn = j8         l[i], l[minn] = l[minn], l[i]9     print l

插入排序:

 1 def insert(l): 2     length = len(l) 3     for i in range(1,length): 4         key = l[i] 5         j = i - 1 6         while j > 0 and l[j] > key: 7             l[j+1] = l[j] 8             j -= 1 9         l[j+1] = key10     print l

快速排序:

(1)传统版

 1 def quick(l, left, right): 2     if left < right: 3         pivot = partition(l, left, right) 4         quick(l, left, pivot - 1) 5         quick(l, pivot + 1, right) 6  7  8 def partition(l, left, right): 9     pivot = l[left]10     i, j = left, right11     while i < j:12         while i < j and l[j] >= pivot:13             j -= 114         if i < j:15             l[i] = l[j]16             i += 117         while i < j and l[i] <= pivot:18             i += 119         if i < j:20             l[j] = l[i]21             j -= 122     l[i] = pivot23     return i

(2)简易版

1 def quick_simple(l):2     if len(l) > 1:3         return quick_simple( [i for i in l[1:] if i < l[0]] ) + l[0:1] + quick_simple( [j for j in l[1:] if j >= l[0]] )4     else:5         return l

未完待续...