Heap Sort using Python STL

Steps:

  1. Import the Python STL library β€œheapqβ€œ.
  2. Convert the input list into a heap using the β€œheapify” function from heapq.
  3. Create an empty list β€œresult” to store the sorted elements.
  4. Iterate over the heap and extract the minimum element using β€œheappop” function from heapq and append it to the β€œresult” list.
  5. Return the β€œresult” list as the sorted output.

Python3




import heapq
 
# Function to perform the sorting using
# heaop sort
def heap_sort(arr):
    heapq.heapify(arr)
    result = []
    while arr:
        result.append(heapq.heappop(arr))
    return result
   
# Driver Code
arr = [60, 20, 40, 70, 30, 10]
print("Input Array: ", arr)
print("Sorted Array: ", heap_sort(arr))


Output

Input Array:  [60, 20, 40, 70, 30, 10]
Sorted Array:  [10, 20, 30, 40, 60, 70]


Time Complexity: O(n log n), where β€œn” is the size of the input list. 
Auxiliary Space: O(1).

Please refer complete article on Heap Sort for more details!



Python Program for Heap Sort

Pre-requisite: What is Heap Sort?

Heapsort is a comparison-based sorting technique based on a Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element.

Similar Reads

Python Program for Heap Sort

The given Python code implements the Heap Sort algorithm, which is an efficient comparison-based sorting method. Heap Sort works by building a binary heap and repeatedly extracting the maximum element (in the case of a max heap) from the heap, which is then placed at the end of the sorted portion of the array. The code comprises three main functions: heapify, heapSort, and the driver code....

Heap Sort using Python STL

...