Code:
#!/usr/bin/env python#Coding=utf-8Importrandom,copydefHeap_sort_helper (lst,left,right):#Max HeapifyCurrent_value =Lst[left] child= 2 * left + 1 while(Child <=Right ):if(Child < Right andLst[child] < lst[child+1]): child= child + 1if(Current_value >Lst[child]): Break Else: lst[( child-1) >>1] =Lst[child] child= 2 * child + 1lst[( child-1) >>1] =Current_valuedefHeap_sort (LST):#Build Heap forIinchRange (len (LST)-1) >>1,-1,-1): Heap_sort_helper (Lst,i,len (LST)-1) forIinchRange (len (LST) -1,0,-1): lst[i],lst[0]=Lst[0],lst[i] Heap_sort_helper (lst,0,i-1)if __name__=="__main__": LST= [Random.randint (0,20) forIinchRange (10)] Lst2=copy.deepcopy (LST) lst2.sort ()Print(LST)Print(LST2) heap_sort (LST)Print(LST)
Test data:
[18, 3, 1, 20, 7, 5, 4, 10, 16, 6]
[1, 3, 4, 5, 6, 7, 10, 16, 18, 20]
[1, 3, 4, 5, 6, 7, 10, 16, 18, 20]
[Python] Heap Sort in Python