Open In App

Row wise sorting a 2D array

Last Updated : 03 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a 2D array, sort each row of this array and print the result.

Examples: 

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

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

The idea is simple, we traverse through each row and call sort for it. Below are sort functions for reference in different languages.

Arrays.sort() in Java
sort() in C++
sort() in Python
sort() in JavaScript

sort() in PHP
qsort() in C

C++
#include <bits/stdc++.h>
using namespace std;

void sortRows(vector<vector<int>> &mat) {
  for (auto &row : mat)
    sort(row.begin(), row.end());
}

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

  sortRows(mat);

  cout << "[\n";
  for (auto &row : mat) {
    cout << "  [";
    for (int j = 0; j < row.size(); j++) {
      if (j > 0) cout << ", ";
      cout << row[j];
    }
    cout << "]\n";
  }
  cout << "]\n";
}
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]
]

Time Complexity: O(r*c*log(c)) where r is the number of rows and c is the number of columns.
Auxiliary Space: O(1)



Next Article
Article Tags :
Practice Tags :

Similar Reads