对于升序堆排序,您可以使用以下代码:
def heapSort(a):
count = len(a)
heapify(a, count)
end = count-1
while end > 0:
a[end], a[0] = a[0], a[end]
end = end - 1
siftDown(a, 0, end)
def heapify(a, count):
start = math.floor((count - 1) / 2)
while start >= 0:
siftDown(a, start, count-1)
start = start - 1
def siftDown(a, start, end):
root = start
while root * 2 + 1 <= end:
child = root * 2 + 1
swap = root
if a[swap] < a[child]:
swap = child
if child+1 <= end and a[swap] < a[child+1]:
swap = child + 1
if swap != root:
a[root], a[swap] = a[swap], a[root]
root = swap
else:
return
或者您可以使用以下代码:
def heapSortDown(lst):
for start in range(math.floor((len(lst)-2)/2), -1, -1):
sift(lst, start, len(lst)-1)
for end in range(len(lst)-1, 0, -1):
lst[end], lst[0] = lst[0], lst[end]
sift(lst, 0, end - 1)
return lst
def sift(lst, start, end):
root = start
while True:
child = root * 2 + 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 heapSortDown(lst):
for start in range(math.floor((len(lst)-2)/2), -1, -1):
sift(lst, start, len(lst)-1)
for end in range(len(lst)-1, 0, -1):
lst[end], lst[0] = lst[0], lst[end]
sift(lst, 0, end - 1)
return lst
def sift(lst, start, end):
root = start
while True:
child = root * 2 + 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