w3resource

Python Exercise: 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 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 heap queue algorithm: Sort a given list of elements in ascending order using Heap queue algorithm.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


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 Python skills with w3resource's quiz


Python: Tips of the Day

Returns every nth element in a list

Example:

def tips_every_nth(lst, nth):
  return lst[nth - 1::nth]

print(tips_every_nth([1, 2, 3, 4, 5, 6, 7, 8, 9], 3))]

Output:

[3, 6, 9]