Def adjust (a, root, n): k = a[root-1] c = root * 2 while c <= n: &NBSP;&NBSP;&NBSP;&NBSP;IF&NBSP;C&NBSP;+&NBSP;1&NBSP;<=&NBSP;N&NBSP;AND&NBSP;A[C]&NBSP;>&NBSP;A[C-1]: c += 1 if a[c-1] <= k: &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;BREAK&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;A[C/2-1]&NBSP;=&NBSP;A[C-1] c *= 2 a[c/2-1] = Kdef heapsort (a): n = len (a) for i in xrange (n / 2, 0, -1): adjust (a, I, n) &NBSP;&NBSP;&NBSp; for i in xrange (n - 1, 0, -1): a[0], a[i] = a[i], a[0] adjust ( a, 1, i) if __name__ == ' __main__ ': from random Import shuffle data = range (+) shuffle (data) print data heapsort (data) print data
Liu Shuo teacher Python Boutique Courses:
" Python advanced Programming Skills Combat":
" python algorithm Combat video Course":
" Python scientific Computing-numpy Combat Course": < Strong style= "padding:0px;margin:0px;" >
panda tv Live room:
http://www.panda.tv/671023
[Shuo. Love Python] Heapsort (Heap sort)