def heapSort1(alist): def lchild(i): return 2*(i+1) - 1 def rchild(i): return 2*(i+1) def parent(i): return (i+1)/2 - 1 def swap(i, j): alist[i], alist[j] = alist[j], alist[i] def percolateUp(i): while i > 0: if alist[i] < alist[parent(i)]: return swap(i, parent(i)) i = parent(i) def percolateDown(max): # heap runs from 0 through max, but root (0) may be out of place; # swap it with its largest child, moving down the tree i = 0 while True: lc = lchild(i); rc = rchild(i) if lc > max: return if rc <= max and alist[rc] > alist[lc] and alist[i] < alist[rc]: swap(i, rc) i = rc elif alist[i] < alist[lc]: swap(i, lc) i = lc else: return # build heap for i in range(1, len(alist)): percolateUp(i) # extract sorted list for i in range(len(alist)-1, 0, -1): swap(0, i) percolateDown(i-1) def heapSort2(alist): def percolateDown(i, high): # parents are larger than children t = alist[i] while True: j = i * 2 + 1 k = j + 1 if j < high: pj = alist[j] if k < high: pk = alist[k] if k < high and pk >= pj: j = k; pj = pk if j >= high or t >= pj: break alist[i] = pj i = j alist[i] = t # build heap for i in range(len(alist)/2, -1, -1): # for all internal nodes percolateDown(i, len(alist)) # extract sorted list for i in range(len(alist)-1, 0, -1): # for all nodes alist[0], alist[i] = alist[i], alist[0] percolateDown(0, i)