Row wise sorting a 2D array (original) (raw)
Last Updated : 03 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
C++ `
#include <bits/stdc++.h> using namespace std;
void sortRows(vector<vector> &mat) { for (auto &row : mat) sort(row.begin(), row.end()); }
int main() { vector<vector> 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> 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)
Similar Reads
- Sort a Rotated Sorted Array You are given a rotated sorted array and your aim is to restore its original sort in place.Expected to use O(1) extra space and O(n) time complexity. Examples: Input : [3, 4, 1, 2] Output : [1, 2, 3, 4] Input : [2, 3, 4, 1] Output : [1, 2, 3, 4] We find the point of rotation. Then we rotate array us 11 min read
- Sort an array in wave form Given an unsorted array of integers, sort the array into a wave array. An array arr[0..n-1] is sorted in wave form if: arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= .....Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80}Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} Explanation: here you 9 min read
- Find median in row wise sorted matrix Given a row-wise sorted matrix mat[][] of order n * m, where the number of rows and columns are always odd. The task is to find the median of the matrix.Note: Median is the middle number in a sorted ascending or descending list of numbers. In case of an even number of elements return the left median 15+ min read
- 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
- Sorting a dynamic 2-dimensional array of Strings Prerequisite: How to dynamically allocate a 2D array in C? Double pointer: A pointer pointing to another pointer is known as a Double pointer. To represent the double pointer ' ** ' is used. Double pointer is also called as pointer to pointer. Example: Input: Geeks, Gfg, Placement, Sudo, Gate Output 5 min read
- Sorted Array to Wave Form Given a sorted array of integers, the task is to sort the array into a wave array. An array arr[0..n-1] is sorted in wave form if:arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= .....Examples:Input: arr[] = {1, 2, 3, 4, 5}Output: arr[] = {2, 1, 4, 3, 5} Explanation: The output array 3 min read
- Sort given words as Array of Strings Given an array of strings Arr[]. The task is to sort them in lexicographic order. Examples: Input: Arr[] = {"sort", "this", "list"}Output: [list, sort, this] Input: Arr[] = {"sun", "earth", "mars", "mercury"}Output: [earth, mars, mercury, sun] Selection Sort Approach: The same problem can also be so 15+ 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
- Sorting an Array in Bash using Insertion Sort Given an array, arr[] of size N, the task is to sort the array in ascending order using Insertion Sort in bash scripting. Examples: Input: arr[] = {9, 7, 2, 5}Output: 2 5 7 9Explanation: The array in sorted order is {2, 5, 7, 9} Input: arr[] = {3, 2, 1}Output: 1 2 3Explanation: The array in sorted o 2 min read