Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Row wise sorting a 2D array
Next article icon

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
Row wise sorting a 2D array

S

Shivani2609
Improve
Article Tags :
  • Sorting
  • Matrix
  • DSA
  • Java-Arrays
Practice Tags :
  • Matrix
  • Sorting

Similar Reads

    Sort the matrix row-wise and column-wise
    Given a n x n matrix. The problem is to sort the matrix row-wise and column wise. Examples: Input : mat[][] = { {4, 1, 3}, {9, 6, 8}, {5, 2, 7} } Output : 1 3 4 2 5 7 6 8 9 Input : mat[][] = { {12, 7, 1, 8}, {20, 9, 11, 2}, {15, 4, 5, 13}, {3, 18, 10, 6} } Output : 1 5 8 12 2 6 10 15 3 7 11 18 4 9 1
    9 min read
    Emulating a 2-d array using 1-d array
    How to convert a 2-d array of size (m x n) into 1-d array and how to store the element at position [i, j] of 2-d array in 1-d array? Clearly, the size of 1-d array is the number of elements in 2-d array i.e. m x n). If the elements in the 2-d array are stored in row-major order. Then, the element at
    5 min read
    How to sort an array in a single loop?
    Given an array of size N, the task is to sort this array using a single loop.How the array is sorted usually? There are many ways by which the array can be sorted in ascending order, like: Selection SortBinary SortMerge SortRadix SortInsertion Sort, etc In any of these methods, more than 1 loops is
    12 min read
    Array Sorting - Practice Problems
    Sorting an array means arranging the elements of the array in a certain order. Generally sorting in an array is done to arrange the elements in increasing or decreasing order. Problem statement: Given an array of integers arr, the task is to sort the array in ascending order and return it, without u
    9 min read
    C Program to sort rows of the Matrix
    Given a matrix arr[][] of dimensions N * M, the task is to sort the matrix such that each row is sorted and the first element of each row is greater than or equal to the last element of the previous row. Examples: Input: N = 3, M = 3, arr[][] = {{7, 8, 9}, {5, 6, 4}, {3, 1, 2}}Output:1 2 34 5 67 8 9
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences