Search code examples
pythonpython-3.xalgorithmheapsort

Python heapsort implementation explanation


This is a python3 implementation of heapsort where n is the size of the heap.

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) 

I understand heapify function and what is it doing. I see a problem in max heap though:

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

from what i have researched i think i need to build max heap on non -leaf node only which should be 0 ... n/2.so is the range correct here?

Also i am having trouble understanding the last part:

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

how is this range working here from n-1 ... 0 with step=-1?


Solution

  • GeeksforGeeks Code for HeapSort in c++

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

    Reference:-

    1. GeeksforGeeks

    PseudoCode For Heapsort in CLRS book

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

    So Yes you are right. Heapfying only Non-Leaf Nodes are enough.

    As for your second question:-

    PseudoCode

    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.