defbubble_sort(lists): # 冒泡排序 count = len(lists) for i in range(0, count): for j in range(i + 1, count): if lists[i] > lists[j]: lists[i], lists[j] = lists[j], lists[i] return lists
defselect_sort(lists): # 选择排序 count = len(lists) for i in range(0, count): min = i for j in range(i + 1, count): if lists[min] > lists[j]: min = j lists[min], lists[i] = lists[i], lists[min] return lists
defshell_sort(lists): # 希尔排序 count = len(lists) step = 2 group = count / step while group > 0: for i in range(0, group): j = i + group while j < count: k = j - group key = lists[j] while k >= 0: if lists[k] > key: lists[k + group] = lists[k] lists[k] = key k -= group j += group group /= step return lists
defmerge(left, right): i, j = 0, 0 result = [] while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result += left[i:] result += right[j:] return result defmerge_sort(lists): # 归并排序 if len(lists) <= 1: return lists num = len(lists) / 2 left = merge_sort(lists[:num]) right = merge_sort(lists[num:]) return merge(left, right)
defquick_sort(lists, left, right): # 快速排序 if left >= right: return lists key = lists[left]#最左边的值 low = left #最低的id high = right #最高的id while left < right: while left < right and lists[right] >= key: right -= 1#从右边找到大于左边的 lists[left] = lists[right] while left < right and lists[left] <= key: left += 1#从左边找到小于右边的 lists[right] = lists[left] lists[right] = key quick_sort(lists, low, left - 1) quick_sort(lists, left + 1, high) return lists
defadjust_heap(lists, i, size):#调整堆 lchild = 2 * i + 1#左子节点 rchild = 2 * i + 2#右子节点 max = i #父节点 if i < size / 2: #父节点非叶子节点 if lchild < size and lists[lchild] > lists[max]: max = lchild #左叶子节点比父节点大 if rchild < size and lists[rchild] > lists[max]: max = rchild #右叶子节点比父节点大 if max != i: #父节点不是最大 lists[max], lists[i] = lists[i], lists[max] adjust_heap(lists, max, size) #父节点变化重新调整 defbuild_heap(lists, size):#创建堆 for i in range(0, (size/2))[::-1]: #从非叶子节点底部开始调整 adjust_heap(lists, i, size) defheap_sort(lists): size = len(lists) build_heap(lists, size) #堆排序 for i in range(0, size)[::-1]: lists[0], lists[i] = lists[i], lists[0] #顶部为最大值放到最后 adjust_heap(lists, 0, i) #重新调整剩余元素
defcountingSort(alist,k): n=len(alist) b=[0for i in xrange(n)] #结果数组 c=[0for i in xrange(k+1)] #范围数组 for i in alist: c[i]+=1 for i in xrange(1,len(c)): c[i]=c[i-1]+c[i] #累加 for i in alist: b[c[i]-1]=i #c[i]为alist中i的个数 c[i]-=1 return b if __name__=='__main__': a=[random.randint(0,100) for i in xrange(100)] print countingSort(a,100)
import math defradix_sort(lists, radix=10): k = int(math.ceil(math.log(max(lists), radix))) bucket = [[] for i in range(radix)] for i in range(1, k+1): for j in lists: bucket[j/(radix**(i-1)) % (radix**i)].append(j) del lists[:] for z in bucket: lists += z del z[:] return lists