Last active
September 14, 2018 05:16
-
-
Save Xifeng2009/603169e90e5144ac9df51bbcc4cb058b to your computer and use it in GitHub Desktop.
堆排序
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/envpython | |
#-*-coding:utf-8-*- | |
def heap_sort(lst): | |
for startinrange((len(lst)-2)/2,-1,-1): | |
sift_down(lst,start,len(lst)-1) | |
for endinrange(len(lst)-1,0,-1): | |
lst[0],lst[end]=lst[end],lst[0] | |
sift_down(lst,0,end-1) | |
return lst | |
def sift_down(lst,start,end): | |
root=start | |
while True: | |
child=2*root+1 | |
if child>end: | |
break | |
if child+1<=end and lst[child]<lst[child+1]: | |
child+=1 | |
if lst[root]<lst[child]: | |
lst[root],lst[child]=lst[child],lst[root] | |
root=child | |
else: | |
break | |
def main(): | |
l=[9,2,1,7,6,8,5,3,4] | |
heap_sort(l) | |
if__name__=="__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment