VOOZH about

URL: https://www.geeksforgeeks.org/dsa/row-wise-sorting-2d-array/

⇱ Row wise sorting a 2D array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Row wise sorting a 2D array

Last Updated : 3 Apr, 2025

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


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)

Comment
Article Tags: