Print Elements in Sorted Order Using Row-Column Wise Sorted Matrix

Understanding the Problem

The goal is to print all elements of a row-column wise sorted matrix in sorted order.

Method 1: Using a Combined Array

This method combines all elements into a single array and then sorts it.

def print_sorted(matrix):
    combined = []

    # Combine all elements into a single array
    for row in matrix:
        combined.extend(row)

    # Sort the combined array
    combined.sort()

    # Print the sorted elements
    print(" ".join(map(str, combined)))

# Example usage
matrix = [
    [10, 20, 30],
    [15, 25, 35],
    [27, 29, 37],
    [32, 33, 38]
]
print("Sorted elements:", end=" ")
print_sorted(matrix)
            

Output:

Sorted elements: 10 15 20 25 27 29 30 32 33 35 37 38

Method 2: Using a Min-Heap

This method uses a min-heap to print elements in sorted order.

import heapq

def print_sorted(matrix):
    min_heap = []

    # Push all elements into the min-heap
    for row in matrix:
        for num in row:
            heapq.heappush(min_heap, num)

    # Print elements in sorted order
    while min_heap:
        print(heapq.heappop(min_heap), end=" ")
    print()

# Example usage
matrix = [
    [10, 20, 30],
    [15, 25, 35],
    [27, 29, 37],
    [32, 33, 38]
]
print("Sorted elements:", end=" ")
print_sorted(matrix)
            

Output:

Sorted elements: 10 15 20 25 27 29 30 32 33 35 37 38

Method 3: Using Two-Pointer Technique

This method uses a two-pointer technique to print elements in sorted order.

def print_sorted(matrix):
    rows = len(matrix)
    cols = len(matrix[0])
    i, j = 0, cols - 1  # Start from the top-right corner

    while i < rows and j >= 0:
        print(matrix[i][j], end=" ")
        if j == 0:
            i += 1  # Move down if we reach the leftmost column
        else:
            j -= 1  # Move left
    print()

# Example usage
matrix = [
    [10, 20, 30],
    [15, 25, 35],
    [27, 29, 37],
    [32, 33, 38]
]
print("Sorted elements:", end=" ")
print_sorted(matrix)
            

Output:

Sorted elements: 10 15 20 25 27 29 30 32 33 35 37 38