5 Best Ways to Sort a Matrix Row-wise and Column-wise Using Python

πŸ’‘ Problem Formulation: Sorting a matrix in Python can be a common task, whether for data analysis or algorithm development. Specifically, we may want to sort a two-dimensional array, or matrix, so that the elements of each row are in ascending order, followed by sorting each column in ascending order. For instance, given the matrix [[3, 2, 1], [9, 8, 7]], the desired output after row-wise sorting would be [[1, 2, 3], [7, 8, 9]], and post column-wise sorting would be [[1, 2, 3], [7, 8, 9]].

Method 1: Using Nested Loops

This method involves two steps: first sorting each row using a simple Python sorting function, and then sorting the columns. This is achieved by transposing the matrix, sorting each row of the transposed matrix (which are originally columns), and then transposing it back. It’s a straightforward method that’s easy to understand but might not be the most efficient for large matrices due to the nested loops involved.

Here’s an example:

matrix = [[3, 2, 1], [9, 8, 7]]

# Sort rows
matrix = [sorted(row) for row in matrix]

# Transpose, sort columns, and transpose back
transpose = list(map(list, zip(*matrix)))
matrix = [sorted(row) for row in transpose]
matrix = list(map(list, zip(*matrix)))

print(matrix)

The output will be:

[[1, 2, 3], [7, 8, 9]]

In this snippet, the rows are sorted in ascending order first. Then, the matrix is transposed (columns become rows), and each ‘new’ row is sorted, which corresponds to sorting the columns. Finally, the matrix is transposed back to its original orientation. This method is ideal for smaller matrices where performance isn’t a critical concern.

Method 2: Using NumPy library

For handling matrices efficiently, the NumPy library is a powerful tool. It provides a function numpy.sort() that can sort along a specified axis. This method is more optimized than nested loops and works well with large datasets. It requires less code and leverages NumPy’s efficiency in handling numerical data.

Here’s an example:

import numpy as np

matrix = np.array([[3, 2, 1], [9, 8, 7]])

# Sort rows
matrix = np.sort(matrix, axis=1)

# Sort columns
matrix = np.sort(matrix, axis=0)

print(matrix)

The output will be:

[[1 2 3]
 [7 8 9]]

This code first sorts each row of the matrix with np.sort(matrix, axis=1) then sorts each column with np.sort(matrix, axis=0). Because it leverages NumPy’s optimized sorting algorithm, this method is much faster and should be preferred for numeric data analysis or whenever performance is a concern.

Method 3: Using List Comprehension

List comprehension offers a more Pythonic and concise way to sort matrices. Similar to the nested loops approach, it processes rows first and then columns, leveraging the power of list comprehension for code conciseness and readability. This method is a favored style in Python and performs well with small to medium-sized matrices.

Here’s an example:

matrix = [[3, 2, 1], [9, 8, 7]]

# Sort rows
matrix = [sorted(row) for row in matrix]

# Sort columns using list comprehension
matrix = list(zip(*[sorted(col) for col in zip(*matrix)]))

print(matrix)

The output will be:

[(1, 2, 3), (7, 8, 9)]

This code utilizes list comprehension to sort rows, then transpose the matrix, sort the columns (now rows), and transpose it back. As with Method 1, this is a more Pythonic approach and is succinct, though it may not be the most optimal for very large matrices in terms of efficiency.

Method 4: Using the Sorted function with a Custom Key

The sorted() function in Python allows for custom sort keys. By using a custom key function, you can sort the matrix first by rows and then by columns in a stride. This method requires a good understanding of how sort keys work and may not be the most intuitive, but it’s quite flexible and allows for complex sorting criteria.

Here’s an example:

matrix = [[3, 2, 1], [9, 8, 7]]

# Sort rows
for i in range(len(matrix)):
    matrix[i] = sorted(matrix[i])

# Sort columns using a custom key
matrix.sort(key=lambda x: x[0])

print(matrix)

The output will be:

[[1, 2, 3], [7, 8, 9]]

This code sorts each row with a standard sort, then it uses the matrix.sort() method to sort based on the first element of each rowβ€”effectively this sorts the columns assuming each row is already sorted. This method can be useful when you want to apply complex sort criteria.

Bonus One-Liner Method 5: Using Advanced List Comprehension and Unpacking

Python’s advanced list comprehension and unpacking features can be utilized to come up with a one-liner solution. While it is not always advisable to favor one-liners over readability, it can be a fun exercise to condense the process into a single line of code. This method is primarily for those who appreciate Python’s capability for concise expressions and already have a strong understanding of list comprehension and the unpacking operator.

Here’s an example:

matrix = [[3, 2, 1], [9, 8, 7]]

# Sort rows and columns in a single line
matrix = list(map(list, zip(*[sorted(col) for col in zip(*[sorted(row) for row in matrix])])))

print(matrix)

The output will be:

[[1, 2, 3], [7, 8, 9]]

This one-liner sorts the rows of the matrix inside a list comprehension, transposes and sorts the columns (now rows), before finally transposing it back all in one chained statement. While it showcases the elegance of Python, it might hinder readability and consequently maintainability.

Summary/Discussion

  • Method 1: Nested Loops. Easy to understand. Not highly efficient for large matrices.
  • Method 2: NumPy Library. Highly efficient and compact. Requires external library and familiarity with NumPy.
  • Method 3: List Comprehension. Pythonic and readable. Efficiency decreases with matrix size.
  • Method 4: Sorted with Custom Key. Flexible and complex sorting. Not intuitive for beginners.
  • Method 5: Advanced One-Liner. Elegant and powerful. Can be unreadable and hard to maintain.