Ticker

20/recent/ticker-posts

Heap Sort Algorithm in Python: Understanding and Implementation

Sorting is an important task in programming, and there are many algorithms available to perform this task. Heap Sort is one of the popular sorting algorithms that can be implemented using Python. In this blog post, we will discuss what Heap Sort is, how it works, and how to implement it in Python.


What is Heap Sort?

Heap Sort is a sorting algorithm that uses a binary heap data structure to sort an array in ascending or descending order. It was invented by J. W. J. Williams in 1964. Heap Sort first builds a binary heap from the input array and then repeatedly extracts the maximum element from the heap and places it at the end of the sorted array.


How does Heap Sort work?

Heap Sort works by first building a binary heap from the input array. A binary heap is a complete binary tree where every node has a value greater than or equal to its children in a max heap, or every node has a value less than or equal to its children in a min heap.

Once the binary heap is built, Heap Sort repeatedly extracts the maximum (or minimum) element from the heap and places it at the end of the sorted array. This process is repeated until all elements have been extracted and placed in the sorted array.


The following steps are involved in Heap Sort:

Build a binary heap from the input array.

Extract the maximum (or minimum) element from the heap and place it at the end of the sorted array.

Heapify the remaining elements of the heap.

Repeat steps 2-3 until all elements have been extracted and placed in the sorted array.

Implementation of Heap Sort in Python


Now that we have an understanding of how Heap Sort works, let's take a look at how to implement it in Python. We will implement Heap Sort using a max heap, which means that the largest element will be at the root of the heap.



def heapify(arr, n, i):

    largest = i

    l = 2 * i + 1

    r = 2 * i + 2


    if l < n and arr[l] > arr[largest]:

        largest = l


    if r < n and arr[r] > arr[largest]:

        largest = r


    if largest != i:

        arr[i], arr[largest] = arr[largest], arr[i]

        heapify(arr, n, largest)


In the above code, we define two functions: heapify and heap_sort. The heapify function is used to maintain the max heap property, and the heap_sort function is used to sort the input array using Heap Sort.

The heapify function takes three arguments: arr, n, and i. arr is the input array, n is the size of the heap, and i is the index of the node to be heapified.

The heap_sort function takes one argument: arr, which is the input array to be sorted. The function first builds a max heap from the input array by calling heapify on each node of the heap in reverse order. Then, the function repeatedly extracts the maximum element from the heap and places it at the end of the sorted array by swapping the first and last elements of the heap_sort` function as follows:



def heap_sort(arr):

    n = len(arr)


    # Build a max heap from the input array

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

        heapify(arr, n, i)


    # Extract the maximum element from the heap and place it at the end of the sorted array

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

        arr[0], arr[i] = arr[i], arr[0]

        heapify(arr, i, 0)

    

    return arr


Let's walk through the code step by step:

We first initialize n to be the length of the input array arr.

We then build a max heap from the input array by iterating over each node in the heap in reverse order, starting from the last non-leaf node. We call heapify on each node to ensure that the subtree rooted at that node satisfies the max heap property.

Once the max heap is built, we repeatedly extract the maximum element from the heap and place it at the end of the sorted array. We do this by swapping the first element (which is the maximum element in a max heap) with the last element, and then calling heapify on the remaining elements to ensure that they satisfy the max heap property.

We repeat this process until all elements have been extracted from the heap and placed in the sorted array.

Finally, we return the sorted array.


Conclusion

Heap Sort is a simple and efficient sorting algorithm that can be implemented using Python. It works by building a binary heap from the input array and repeatedly extracting the maximum (or minimum) element from the heap and placing it at the end of the sorted array. The implementation of Heap Sort in Python requires two functions: heapify and heap_sort. The heapify function is used to maintain the max heap property, and the heap_sort function is used to sort the input array using Heap Sort.


Here is detail on each sorting algorithm in python

Post a Comment

0 Comments