To print all elements in sorted order from row and column wise sorted matrix in Python



In Python, we may go through the matrices that are sorted in a particular order. A common case is a matrix where each row and each column is sorted in increasing order, and this does not mean that the entire matrix is sorted.

In such cases, we need to extract all elements and print them in a fully sorted order.

Row and Column-wise Sorted Matrix?

A row and column-wise sorted matrix means each row is sorted from left to right, and each column is sorted from top to bottom.

For example, let's consider the following matrix -

matrix = [
    [10, 20, 30, 40],
    [15, 25, 35, 45],
    [27, 29, 37, 48],
    [32, 33, 39, 50]
]

In the above matrix, both rows and columns are sorted, but the entire matrix is not sorted. When we want to print the elements in a single sorted list as follows, then we can use different methods as discussed below -

[10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50]

Sorting using Min Heap

A Min Heap is a binary tree-based data structure where the smallest element is always at the root. Python has the heapq module to implement a min heap.

As we discussed above, when we are working with a matrix where each row and each column is sorted in ascending order, then it seems as if the entire matrix is sorted. We can print or retrieve all elements in sorted order, and we can use the Min Heap.

Following are the steps to be followed to sort the elements in a matrix using a Min Heap -

  • First, push the first element of each row into a min-heap.
  • Next, pop the smallest element from the heap and add it to the result list.
  • After that, push the next element from the same row into the heap if it exists.
  • Repeat the above step until all elements are processed.

Example

Following is the example, in which we are using the heapq module to implement the Min Heap to sort all the elements from row and column in a matrix -

import heapq

def sort_matrix_using_min_heap(matrix):
   if not matrix or not matrix[0]:
      return []

   n = len(matrix)
   m = len(matrix[0])

   # Min heap: each item is a tuple (value, row index, column index)
   min_heap = []
    
   # Step 1: Push the first element of each row into the heap
   for i in range(n):
      heapq.heappush(min_heap, (matrix[i][0], i, 0))

   result = []

   # Step 2: Extract min and push next element of the same row
   while min_heap:
      val, r, c = heapq.heappop(min_heap)
      result.append(val)

      if c + 1 < m:
         next_val = matrix[r][c + 1]
         heapq.heappush(min_heap, (next_val, r, c + 1))

   return result

# Sample matrix
matrix = [
    [10, 20, 30, 40],
    [15, 25, 35, 45],
    [27, 29, 37, 48],
    [32, 33, 39, 50]
]

# Print sorted result
print("Sorted Elements:", sort_matrix_using_min_heap(matrix))

Here is the output of the above example -

Sorted Elements: [10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50]
Updated on: 2025-06-20T19:18:12+05:30

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements