Python: Sort a given list of elements in ascending order using Heap queue algorithm
Python heap queue algorithm: Exercise-6 with Solution
Write a Python program to sort a given list of elements in ascending order using the heap queue algorithm.
Sample Solution:
Python Code:
import heapq as hq
nums_list = [18, 14, 10, 9, 8, 7, 9, 3, 2, 4, 1]
print("Original list:")
print(nums_list)
hq.heapify(nums_list)
s_result = [hq.heappop(nums_list) for i in range(len(nums_list))]
print("\nSorted list:")
print(s_result)
Sample Output:
Original list: [18, 14, 10, 9, 8, 7, 9, 3, 2, 4, 1] Sorted list: [1, 2, 3, 4, 7, 8, 9, 9, 10, 14, 18]
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to delete the smallest element from the given Heap and then inserts a new item.
Next: Write a Python program to find the kth largest element in an unsorted array using Heap queue algorithm.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/heap-queue-algorithm/python-heapq-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics