Python heapsort实现说明

问题描述 投票:0回答:1

这是heapsort的python3实现,其中n是堆的大小。

def heapify(arr, n, i): 
    largest = i  
    l = 2 * i + 1     # left = 2*i + 1 
    r = 2 * i + 2     # right = 2*i + 2 

# See if left child of root exists and is 
# greater than root 
if l < n and arr[i] < arr[l]: 
    largest = l 

# See if right child of root exists and is 
# greater than root 
if r < n and arr[largest] < arr[r]: 
    largest = r 

# Change root, if needed 
if largest != i: 
    arr[i],arr[largest] = arr[largest],arr[i] # swap 

    # Heapify the root. 
    heapify(arr, n, largest) 

# The main function to sort an array of given size 
def heapSort(arr): 
   n = len(arr) 

   # Build a maxheap. 
   for i in range(n, -1, -1): 
       heapify(arr, n, i) 

# One by one extract elements 
for i in range(n-1, 0, -1): 
    arr[i], arr[0] = arr[0], arr[i] # swap 
    heapify(arr, i, 0) 

我理解heapify函数以及它在做什么。我看到最大堆中存在问题:

for i in range(n, -1, -1): 

从我所研究的我认为我需要在非叶节点上构建最大堆,它应该是0 ... n / 2.so这里的范围是否正确?

我也无法理解最后一部分:

for i in range(n-1, 0, -1): 
arr[i], arr[0] = arr[0], arr[i] # swap 
heapify(arr, i, 0)

这个范围在n-1 ... 0和step = -1之间是如何工作的?

python python-3.x algorithm heapsort
1个回答
0
投票

GeeksforGeeks C ++中的HeapSort代码

// Build heap (rearrange array) 
for (int i = n / 2 - 1; i >= 0; i--) 
    heapify(arr, n, i); 

参考:-

  1. GeeksforGeeks

CLRS书中的PapsoCode For Heaport

BUILD-MAX-HEAP(A)
    heap-size[A] ← length[A]
    for i ← length[A]/2 downto 1
    do MAX-HEAPIFY(A, i)

所以是的你是对的。仅对非叶节点进行Heapfying就足够了。

至于你的第二个问题: -

伪代码

1.MaxHeapify(Array)
2.So the Array[0] has the maximum element
3.Now exchange Array[0] and Array[n-1] and decrement the size of heap by 1. 
4.So we now have a heap of size n-1 and we again repeat the steps 1,2 and 3 till the index is 0.  
© www.soinside.com 2019 - 2024. All rights reserved.