JavaScript program for Sort the given matrix

Sorting a given matrix using JavaScript is a fundamental operation in programming. Sorting is the process of arranging the elements of a collection or matrix in a particular order. It is essential to make searching and other operations more efficient.

In this article, we will discuss how to sort a given matrix using the JavaScript programming language.

Problem Statement

Given an n x n matrix, we need to sort all elements so that the matrix follows "strict order" - each row is sorted in ascending order, and for any row i where 1 ? i ? n-1, the first element of that row must be greater than or equal to the last element of the previous row (i-1).

Input:  [5, 4, 7]
        [1, 3, 8]
        [2, 9, 6]

Output: [1, 2, 3]
        [4, 5, 6]
        [7, 8, 9]

Method 1: Flatten, Sort, and Rebuild

The simplest approach is to flatten the matrix into a 1D array, sort it, then rebuild the matrix structure:

function sortMatrixSimple(matrix) {
    // Flatten matrix to 1D array
    let flatArray = matrix.flat();
    
    // Sort the flattened array
    flatArray.sort((a, b) => a - b);
    
    // Rebuild matrix structure
    let rows = matrix.length;
    let cols = matrix[0].length;
    let sortedMatrix = [];
    
    for (let i = 0; i < rows; i++) {
        let row = [];
        for (let j = 0; j < cols; j++) {
            row.push(flatArray[i * cols + j]);
        }
        sortedMatrix.push(row);
    }
    
    return sortedMatrix;
}

// Test the function
let matrix = [
    [5, 4, 7],
    [1, 3, 8],
    [2, 9, 6]
];

console.log("Original Matrix:");
matrix.forEach(row => console.log(row));

let sortedMatrix = sortMatrixSimple(matrix);

console.log("\nSorted Matrix:");
sortedMatrix.forEach(row => console.log(row));
Original Matrix:
[5, 4, 7]
[1, 3, 8]
[2, 9, 6]

Sorted Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Method 2: In-Place Bubble Sort

For educational purposes, we can implement an in-place sorting using bubble sort that treats the matrix as a continuous sequence:

function bubbleSortMatrix(matrix) {
    let rows = matrix.length;
    let cols = matrix[0].length;
    let totalElements = rows * cols;
    
    // Convert 2D coordinates to 1D index
    function getElement(index) {
        let row = Math.floor(index / cols);
        let col = index % cols;
        return matrix[row][col];
    }
    
    // Set element at 1D index
    function setElement(index, value) {
        let row = Math.floor(index / cols);
        let col = index % cols;
        matrix[row][col] = value;
    }
    
    // Bubble sort on flattened representation
    for (let i = 0; i < totalElements - 1; i++) {
        for (let j = 0; j < totalElements - i - 1; j++) {
            if (getElement(j) > getElement(j + 1)) {
                // Swap elements
                let temp = getElement(j);
                setElement(j, getElement(j + 1));
                setElement(j + 1, temp);
            }
        }
    }
    
    return matrix;
}

// Test the function
let matrix2 = [
    [9, 2, 5],
    [7, 1, 4],
    [8, 3, 6]
];

console.log("Original Matrix:");
matrix2.forEach(row => console.log(row));

bubbleSortMatrix(matrix2);

console.log("\nSorted Matrix:");
matrix2.forEach(row => console.log(row));
Original Matrix:
[9, 2, 5]
[7, 1, 4]
[8, 3, 6]

Sorted Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Comparison of Methods

Method Time Complexity Space Complexity Advantages
Flatten & Sort O(n² log n²) O(n²) Simple, uses built-in sort
Bubble Sort O(n?) O(1) In-place, educational value

Practical Example

Here's a complete example with input validation and flexible matrix sizes:

function sortMatrix(matrix) {
    // Input validation
    if (!Array.isArray(matrix) || matrix.length === 0) {
        throw new Error("Invalid matrix input");
    }
    
    // Create a copy to avoid modifying original
    let matrixCopy = matrix.map(row => [...row]);
    
    // Flatten, sort, and rebuild
    let flatArray = matrixCopy.flat().sort((a, b) => a - b);
    
    let rows = matrixCopy.length;
    let cols = matrixCopy[0].length;
    
    // Rebuild matrix
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            matrixCopy[i][j] = flatArray[i * cols + j];
        }
    }
    
    return matrixCopy;
}

// Test with different matrix sizes
let matrices = [
    [[3, 1], [4, 2]],
    [[15, 7, 23], [9, 11, 1], [13, 5, 19]],
    [[8, 3, 6, 12], [2, 9, 4, 1]]
];

matrices.forEach((matrix, index) => {
    console.log(`Matrix ${index + 1}:`);
    console.log("Before:", matrix.map(row => row.join(" ")).join("<br>       "));
    
    let sorted = sortMatrix(matrix);
    console.log("After: ", sorted.map(row => row.join(" ")).join("<br>       "));
    console.log("");
});
Matrix 1:
Before: 3 1
        4 2
After:  1 2
        3 4

Matrix 2:
Before: 15 7 23
        9 11 1
        13 5 19
After:  1 5 7
        9 11 13
        15 19 23

Matrix 3:
Before: 8 3 6 12
        2 9 4 1
After:  1 2 3 4
        6 8 9 12

Conclusion

We've explored two approaches to sort matrices in JavaScript: the efficient flatten-and-sort method and the educational bubble sort approach. The flatten method is recommended for production code due to its better time complexity, while bubble sort helps understand the underlying sorting mechanics.

Updated on: 2026-03-15T23:19:01+05:30

392 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements