Program to implement Heap sort in Python

Program to implement Heap sort in Python

In the python programming article, we are going to learn

  • program to implement heap sort in python

Program to implement Heap sort in Python

The program is as follows:


# Owner : TutorialsInhand Author : Devjeet Roy

def do_heapify(arr, n, i): 
    largest = i 
    l = 2 * i + 1     
    r = 2 * i + 2     
    if l < n and arr[i] < arr[l]: 
        largest = l 
    if r < n and arr[largest] < arr[r]: 
        largest = r  
    if largest != i: 
        arr[i],arr[largest] = arr[largest],arr[i]
        do_heapify(arr, n, largest) 

def heap_sort(arr,l,h):
    n = len(arr)  
    for i in range(n // 2 - 1, -1, -1): 
        do_heapify(arr, n, i)  
    for i in range(n-1, 0, -1): 
        arr[i], arr[0] = arr[0], arr[i] 
        do_heapify(arr, i, 0)
    return arr

if __name__ == "__main__":
    marks = [22,66,43,58,98,42,77,56,66]
    result = heap_sort(marks,0,len(marks)-1)

    print("The sorted marks: ", result)

The output is as follows:


PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python
The sorted marks:  [22, 42, 43, 56, 58, 66, 66, 77, 98]

Few important tips about the program

1. Heapsort is a comparison based sorting technique based on a Binary Heap data structure. 

2. The time complexity is O(nlogn)


heap sort in python


Basic Python Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by

About the Author
Devjeet Roy
Full Stack Web Developer & Blockchain Enthusiast
Page Views :    Published Date : Oct 13,2022  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!