heapq in Python to print all elements in sorted order from row and column wise sorted matrix
Given a row and column wise sorted matrix, we can use the heapq
module in Python to print all the elements in sorted order.
The heapq
module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. It allows us to maintain a heap data structure, which is a binary tree that satisfies the heap property. In a min-heap, the parent node is always smaller than its children, while in a max-heap, the parent node is always larger than its children.
To use heapq
to print all the elements in sorted order from a row and column wise sorted matrix, we can follow these steps:
- Import the
heapq
module. - Create an empty list to store the elements from the matrix.
- Iterate over each row in the matrix.
- For each row, iterate over each element in the row and add it to the list.
- Use the
heapq.heapify()
function to convert the list into a heap. - Use the
heapq.heappop()
function to remove the smallest element from the heap and print it. - Repeat step 6 until the heap is empty.
Here's an example implementation:
import heapq
def print_sorted(matrix):
# Step 2
elements = []
# Step 3
for row in matrix:
# Step 4
for element in row:
elements.append(element)
# Step 5
heapq.heapify(elements)
# Step 6 and 7
while elements:
print(heapq.heappop(elements), end=' ')
Let's test this function with a sample matrix:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print_sorted(matrix)
Output:
1 2 3 4 5 6 7 8 9
Another method to solve this problem is to use the sorted()
function with a key function that returns the element at the current index in the matrix. Here's an example implementation:
def print_sorted(matrix):
# Step 2
elements = []
# Step 3
for row in matrix:
# Step 4
for element in row:
elements.append(element)
# Step 5
sorted_elements = sorted(elements, key=lambda x: (x // len(matrix[0]), x % len(matrix[0])))
# Step 6 and 7
for element in sorted_elements:
print(element, end=' ')
In this implementation, we first create a list of all the elements in the matrix, and then use the sorted()
function to sort the list based on the row and column indices of each element. The key
function returns a tuple of the row and column indices of each element, which is used to sort the list. Finally, we iterate over the sorted list and print each element.
Let's test this function with the same sample matrix:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print_sorted(matrix)
Output:
1 2 3 4 5 6 7 8 9