w3resource

Python: Create a heapsort, pushing all values onto a heap and then popping off the smallest values one at a time


24. Heapsort via Heap Operations

Write a Python program to create a heapsort, pushing all values onto a heap and then popping off the smallest values one at a time.

Sample Solution:

Python Code:

import heapq
def heapsort(h):
    heap = []
    for value in h:
        heapq.heappush(heap, value)
    return [heapq.heappop(heap) for i in range(len(heap))]

print(heapsort([10, 20, 50, 70, 90, 20, 50, 40, 60, 80, 100]))

Sample Output:

[10, 20, 20, 40, 50, 50, 60, 70, 80, 90, 100]

Flowchart:

Python heap queue algorithm: Create a heapsort, pushing all values onto a heap and then popping off the smallest values one at a time.

For more Practice: Solve these Related Problems:

  • Write a Python program to implement heapsort by first pushing all values onto a heap and then repeatedly popping the smallest element to form a sorted list.
  • Write a Python script to demonstrate heapsort using heapq by converting a list to a heap and then extracting all elements in order.
  • Write a Python program to sort a list using heap operations and print both the original and the sorted list.
  • Write a Python function to perform heapsort on a list of integers and then compare the result with the output of Python’s built-in sorted() function.

Go to:


Previous: Write a Python program to push an item on the heap, then pop and return the smallest item from the heap.
Next: Write a Python program to get the two largest and three smallest items from a dataset.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.