Skip to content

Instantly share code, notes, and snippets.

@jasonlvhit
Created March 4, 2014 13:06
Show Gist options
  • Save jasonlvhit/9346203 to your computer and use it in GitHub Desktop.
Save jasonlvhit/9346203 to your computer and use it in GitHub Desktop.
堆排序
#heap sort
#intruduction to algorithm
import sys
from math import floor
def Max_Heapify(data,i):
l = 2*i
r = 2*i + 1
if l <= len(data) - 1 and data[l] > data[i]:
largest = l
else:
largest = i
if r <= len(data) - 1 and data[r] > data[largest]:
largest = r
if int(largest) != i:
data[i], data[int(largest)] = data[int(largest)], data[i]
Max_Heapify(data, int(largest))
def Build_Maxheap(data):
for i in range(floor((len(data) - 1)/2), 0, -1):
Max_Heapify(data,int(i))
def Heap_Sort(data):
Build_Maxheap(data)
for i in range(len(data) - 1, 1, -1):
data[1], data[i] = data[i], data[1]
print(data[i])
del data[i]
Max_Heapify(data, 1)
if __name__ == '__main__':
data = [None]
#data = [None,2,3,2,...]
for i in range(1,len(sys.argv)):
data.append(int(sys.argv[i]))
Heap_Sort(data)
print(data[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment