Row wise sorting a 2D array

Last Updated : 26 Aug, 2026

Given a 2D array, sort the elements of each row in ascending order and print the resulting matrix.

  • Each row is sorted independently without changing the order of elements in other rows.
  • The std::sort() function can be used to sort the elements of each row efficiently.

Examples: 

Input:

[
[77, 11, 22, 3],
[11, 89, 1, 12],
[32, 11, 56, 7],
[11, 22, 44, 33]
]

Output:

[
[3, 11, 22, 77],
[1, 11, 12, 89],
[7, 11, 32, 56],
[11, 22, 33, 44]
]

Input:

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

Output:

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

Approach to Sort Each Row of a 2D Array

The idea is to traverse the matrix row by row and apply std::sort() to each row. Since std::vector provides iterators to the beginning and end of each row, sort(row.begin(), row.end()) sorts that row in ascending order.

Steps

  1. Traverse each row of the 2D array.
  2. Apply std::sort() to the current row.
  3. Repeat until all rows are sorted.
  4. Print the resulting matrix.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// Function to sort each row of the matrix
void sortRows(vector<vector<int>>& mat)
{
    // Traverse each row
    for (auto& row : mat)
    {
        // Sort the current row in ascending order
        sort(row.begin(), row.end());
    }
}

int main()
{
    // Initialize the 2D array
    vector<vector<int>> mat = {
        {77, 11, 22, 3},
        {11, 89, 1, 12},
        {32, 11, 56, 7},
        {11, 22, 44, 33}
    };

    // Sort each row
    sortRows(mat);

    // Print the sorted matrix
    cout << "[\n";

    for (const auto& row : mat)
    {
        cout << "    [";

        for (int j = 0; j < row.size(); j++)
        {
            if (j > 0)
                cout << ", ";

            cout << row[j];
        }

        cout << "]\n";
    }

    cout << "]\n";

    return 0;
} 
C
#include <stdio.h>

#define ROWS 4
#define COLS 4

void sortRow(int row[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (row[j] > row[j + 1]) {
                int temp = row[j];
                row[j] = row[j + 1];
                row[j + 1] = temp;
            }
        }
    }
}

void sortRows(int mat[ROWS][COLS]) {
    for (int i = 0; i < ROWS; i++) {
        sortRow(mat[i], COLS);
    }
}

int main() {
    int mat[ROWS][COLS] = {
        {77, 11, 22, 3},
        {11, 89, 1, 12},
        {32, 11, 56, 7},
        {11, 22, 44, 33}
    };

    sortRows(mat);

    printf("[\n");
    for (int i = 0; i < ROWS; i++) {
        printf("  [");
        for (int j = 0; j < COLS; j++) {
            if (j > 0) printf(", ");
            printf("%d", mat[i][j]);
        }
        printf("]\n");
    }
    printf("]\n");

    return 0;
}
Java
import java.util.Arrays;
import java.util.Collections;

public class Main {
    public static void sortRows(int[][] mat) {
        for (int[] row : mat) {
            Arrays.sort(row);
        }
    }

    public static void main(String[] args) {
        int[][] mat = {
            {77, 11, 22, 3},
            {11, 89, 1, 12},
            {32, 11, 56, 7},
            {11, 22, 44, 33}
        };

        sortRows(mat);

        System.out.println("[");
        for (int[] row : mat) {
            System.out.print("  [");
            for (int j = 0; j < row.length; j++) {
                if (j > 0) System.out.print(", ");
                System.out.print(row[j]);
            }
            System.out.println("]");
        }
        System.out.println("]");
    }
}
Python
def sortRows(mat):
    for row in mat:
        row.sort()

mat = [
    [77, 11, 22, 3],
    [11, 89, 1, 12],
    [32, 11, 56, 7],
    [11, 22, 44, 33]
]

sortRows(mat)

print('[\n', end='')
for row in mat:
    print('  [', end='')
    print(', '.join(map(str, row)), end='')
    print(']')
print(']')
C#
using System;
using System.Collections.Generic;

class Program
{
    static void SortRows(List<List<int>> mat)
    {
        foreach (var row in mat)
        {
            row.Sort();
        }
    }

    static void Main()
    {
        var mat = new List<List<int>>
        {
            new List<int> { 77, 11, 22, 3 },
            new List<int> { 11, 89, 1, 12 },
            new List<int> { 32, 11, 56, 7 },
            new List<int> { 11, 22, 44, 33 }
        };

        SortRows(mat);

        Console.WriteLine("[");
        foreach (var row in mat)
        {
            Console.Write("  [");
            for (int j = 0; j < row.Count; j++)
            {
                if (j > 0) Console.Write(", ");
                Console.Write(row[j]);
            }
            Console.WriteLine("]");
        }
        Console.WriteLine("]");
    }
}
JavaScript
function sortRows(mat) {
    for (let row of mat) {
        row.sort((a, b) => a - b);
    }
}

let mat = [
    [77, 11, 22, 3],
    [11, 89, 1, 12],
    [32, 11, 56, 7],
    [11, 22, 44, 33]
];

sortRows(mat);

console.log('[\n');
for (let row of mat) {
    console.log('  [', row.join(', '), ']');
}
console.log(']');

Output
[
    [3, 11, 22, 77]
    [1, 11, 12, 89]
    [7, 11, 32, 56]
    [11, 22, 33, 44]
]

Explanation: The sortRows() function iterates over every row using a range-based for loop. For each row, sort(row.begin(), row.end()) rearranges its elements in ascending order. The main() function initializes the matrix, calls sortRows(), and then prints the sorted matrix.

Comment