[英]Why doesn't my heapsort work?
我有這個python Heapsort-Code由網絡中的偽代碼制作而成。
但它給出了錯誤的結果。
def heapSortUp(a):
heapifyUp(a, len(a))
end = len(a)-1
while end > 0:
a[end], a[0] = a[0], a[end]
end -= 1
siftUp(a, 0, end)
return a
def heapifyUp(a, count):
end = 1
while end < count:
siftUp(a, 0, end)
end += 1
def siftUp(a, start, end):
child = end
while child > start:
parent = int(math.floor((child-1)/2)) # floor = abrunden
if a[parent] < a[child]:
a[parent], a[child] = a[child], a[parent]
child = parent
else:
return
我特別想使用siftUP版本。
通過計算print heapSortUp([1,5,4,2,9,8,7])
它返回: print heapSortUp([1,5,4,2,9,8,7])
[8, 7, 9, 2, 1, 4, 5, 7, 5]
問題是你需要在heapSortUp(a)
向下移動
def heapSortUp(a):
heapifyUp(a, len(a))
end = len(a)-1
while end > 0:
a[end], a[0] = a[0], a[end]
end -= 1
siftDown(a, 0, end)
return a
你需要篩選的原因是篩選使堆無效。 這可以通過一個簡單的例子來展示。
拿一堆4,3,2,1
。 在排序的一次迭代之后,您將在末尾放置4,在前面放置1。 因此堆看起來像樹一樣
1
3 2
然而,當你篩選你交換1
和2
。 這意味着2具有比3更高的優先級。如果繼續進行排序(如同編寫),則將使數組1,3,2,4
上升
要獲得實際排序,您需要對其進行篩選,以便在第一次迭代后堆看起來像。
3
1 2
我把siftDown實現留給你。
對於升序堆排序,您可以使用以下代碼:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.