How to Sort a Multi-dimensional Array by Value
Last Updated :
11 Oct, 2023
What is Sorting?
Arranging data in an increasing or decreasing fashion according to their values is called Sorting.
Below are shown some processes for sorting arrays of several dimensions.
Sorting a 1-Dimensional array:
We can sort any Dimensional array using the sort method in C++.
Syntax:
sort(arr, arr+N)
Where,
- arr, represents the name of the array.
- arr + N, represents name of the array + size of the array
Time Complexity: O(N * log N)
Auxiliary Space: O(1)
Example:-
C++
#include <algorithm> // for std::sort
#include <iostream>
const int SIZE = 5;
// A comparison function that sorts the array in ascending
// order
bool compare(int a, int b) { return a < b; }
int main()
{
// Initialize the array
int arr[SIZE] = { 3, 5, 1, 2, 4 };
// Sort the array using the compare function
std::sort(arr, arr + SIZE, compare);
// Print the sorted array
for (int i = 0; i < SIZE; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
// code by ksam24000
Java
// Java code for the approach
import java.util.Arrays;
import java.util.Comparator;
public class GFG {
// Driver code
public static void main(String[] args) {
final int SIZE = 5;
// Initialize the array
Integer[] arr = new Integer[SIZE];
arr[0] = 3;
arr[1] = 5;
arr[2] = 1;
arr[3] = 2;
arr[4] = 4;
// Sort the array using the compare function
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
});
// Print the sorted array
for (int i = 0; i < SIZE; i++) {
System.out.print(arr[i] + " ");
}
}
}
Python3
from functools import cmp_to_key
def compare(a, b):
return a - b
def main():
# Initialize the list
arr = [3, 5, 1, 2, 4]
# Sort the list using the compare function
arr = sorted(arr, key=cmp_to_key(compare))
# Print the sorted list
for i in arr:
print(i, end=" ")
main()
C#
using System;
using System.Linq;
class GFG {
static void Main(string[] args) {
const int SIZE = 5;
// Initialize the array
int[] arr = { 3, 5, 1, 2, 4 };
// Sort the array using the compare function
Array.Sort(arr, (a, b) => a.CompareTo(b));
// Print the sorted array
foreach(int num in arr) {
Console.Write(num + " ");
}
}
}
JavaScript
const SIZE = 5;
// A comparison function that sorts the array in ascending
// order
function compare(a, b) {
return a - b;
}
// Initialize the array
let arr = [3, 5, 1, 2, 4];
// Sort the array using the compare function
arr.sort(compare);
// Print the sorted array
for (let i = 0; i < SIZE; i++) {
console.log(arr[i] + " ");
}
Sorting in Multi-Dimensional Array:
1. Sorting a 2 - Dimensional array Case:
When you want to sort the row:
You can consider each row as a one-dimensional array and sort them individually
Syntax:
for( int i=0; i<row; i++) {
sort(arr[i], arr[i]+col)
}
Where,
- row : Total no of row
- col : Total no of col
Time Complexity: O(N * M * log M)
Auxiliary Space: O(1)
When you want to sort the entire matrix:
Syntax:
sort(&arr[0][0], &arr[r-1][col])
Where
- row: Total no of row
- col: Total no of col
Time Complexity: O(N*M log (N*M)) for sorting only and O(N*M) for printing the array
Auxiliary Space: O(1)
Example:-
C++
// C++ code
#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 3
void sortfun(int arr[R][C])
{
// One by one sort
// individual rows.
for (int i = 0; i < R; i++)
sort(arr[i], arr[i] + C);
// Printing the sorted matrix
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++)
cout << (arr[i][j]) << " ";
cout << endl;
}
}
int main()
{
// Initialize the 2D array
int arr[3][3]
= { { 3, 2, 1 }, { 6, 5, 4 }, { 9, 8, 7 } };
// Sort the 2D array using the function
sortfun(arr);
return 0;
}
// code by ksam24000
Java
import java.util.Arrays;
public class Main {
static final int R = 3;
static final int C = 3;
static void sortfun(int arr[][]) {
// One by one sort
// individual rows.
for (int i = 0; i < R; i++) {
Arrays.sort(arr[i]);
}
// Printing the sorted matrix
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int arr[][] = { { 3, 2, 1 }, { 6, 5, 4 }, { 9, 8, 7 } };
// Sort the 2D array using the function
sortfun(arr);
}
}
Python3
# Python3 code
R = 3
C = 3
def sortfun(arr):
# One by one sort
# individual rows.
for i in range(R):
arr[i].sort()
# Printing the sorted matrix
for i in range(R):
for j in range(C):
print(arr[i][j], end=" ")
print()
# Initialize the 2D array
arr = [ [ 3, 2, 1 ], [ 6, 5, 4 ], [ 9, 8, 7 ] ]
# Sort the 2D array using the function
sortfun(arr)
C#
using System;
class Program
{
static int R = 3;
static int C = 3;
static void SortMatrix(int[,] arr)
{
// One by one sort individual rows.
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C - 1; j++)
{
for (int k = 0; k < C - j - 1; k++)
{
if (arr[i, k] > arr[i, k + 1])
{
// Swap elements if they are in the wrong order
int temp = arr[i, k];
arr[i, k] = arr[i, k + 1];
arr[i, k + 1] = temp;
}
}
}
}
// Printing the sorted matrix
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
{
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
}
static void Main()
{
// Initialize the 2D array
int[,] arr = { { 3, 2, 1 }, { 6, 5, 4 }, { 9, 8, 7 } };
// Sort the 2D array using the function
SortMatrix(arr);
}
}
JavaScript
function sortfun(arr) {
// One by one sort
// individual rows.
for (let i = 0; i < R; i++)
arr[i].sort();
// Printing the sorted matrix
for (let i = 0; i < R; i++) {
for (let j = 0; j < C; j++)
console.log(arr[i][j] + " ");
console.log("\n");
}
}
// Initialize the 2D array
const R = 3;
const C = 3;
const arr = [[3, 2, 1], [6, 5, 4], [9, 8, 7]];
// Sort the 2D array using the function
sortfun(arr);
Note: This was for only 2-D array case but for any dimensional array it works the same way.
2. Sorting for a 3-Dimensional Array:
Consider, the three dimensions to be X, Y and Z.
- So, for the first case, where we want to sort it according to the row. The pseudocode will be:
for( int i=0; i<X; i++)
for(int j=0; j<Y; j++)
sort(arr[i][j], arr[i][j]+Z)
Time Complexity: O(X*Y*Z log Z)
Auxiliary Space: O(1)
- Now, for the second case, where we want to sort entire matrix. The pseudocode will be:
sort(&arr[0][0][0], &arr[X-1][Y-1][Z])
Time Complexity: O(X*Y*Z log (X*Y*Z))
Auxiliary Space: O(1)
C++
#include <bits/stdc++.h>
using namespace std;
const int R = 3, C = 3, H = 3;
void sortfun(int arr[][R][C])
{
// One by one sort individual rows.
for (int i = 0; i < H; i++)
for (int j = 0; j < R; j++)
sort(arr[i][j], arr[i][j] + C);
// Printing the sorted matrix
for (int i = 0; i < H; i++) {
cout << "Layer " << i + 1 << ":" << endl;
for (int j = 0; j < R; j++) {
for (int k = 0; k < C; k++)
cout << arr[i][j][k] << " ";
cout << endl;
}
}
}
int main()
{
int arr[H][R][C] = {
{ { 3, 2, 1 }, { 6, 5, 4 }, { 9, 8, 7 } },
{ { 11, 12, 13 }, { 14, 15, 16 }, { 17, 18, 19 } },
{ { 21, 22, 23 }, { 24, 25, 26 }, { 27, 28, 29 } }
};
sortfun(arr);
return 0;
}
Java
import java.util.Arrays;
public class Main {
static final int R = 3;
static final int C = 3;
static final int H = 3;
public static void sortfun(int[][][] arr)
{
// One by one sort individual rows.
for (int i = 0; i < H; i++)
for (int j = 0; j < R; j++)
Arrays.sort(arr[i][j]);
// Printing the sorted matrix
for (int i = 0; i < H; i++) {
System.out.println("Layer " + (i + 1) + ":");
for (int j = 0; j < R; j++) {
for (int k = 0; k < C; k++)
System.out.print(arr[i][j][k] + " ");
System.out.println();
}
}
}
public static void main(String[] args)
{
int[][][] arr
= { { { 3, 2, 1 }, { 6, 5, 4 }, { 9, 8, 7 } },
{ { 11, 12, 13 },
{ 14, 15, 16 },
{ 17, 18, 19 } },
{ { 21, 22, 23 },
{ 24, 25, 26 },
{ 27, 28, 29 } } };
sortfun(arr);
}
}
Python3
R = 3
C = 3
H = 3
def sortfun(arr):
# One by one sort individual rows.
for i in range(H):
for j in range(R):
arr[i][j] = sorted(arr[i][j])
# Printing the sorted matrix
for i in range(H):
print("Layer " + str(i + 1) + ":")
for j in range(R):
for k in range(C):
print(arr[i][j][k], end=" ")
print()
# Initializing the 3D array
arr = [
[[3, 2, 1], [6, 5, 4], [9, 8, 7]],
[[11, 12, 13], [14, 15, 16], [17, 18, 19]],
[[21, 22, 23], [24, 25, 26], [27, 28, 29]]
]
sortfun(arr)
#This code is contributed by Akash Jha
C#
using System;
public class Program
{
public static void Main()
{
int[,,] arr = new int[3, 3, 3] {
{ { 3, 2, 1 }, { 6, 5, 4 }, { 9, 8, 7 } },
{ { 11, 12, 13 }, { 14, 15, 16 }, { 17, 18, 19 } },
{ { 21, 22, 23 }, { 24, 25, 26 }, { 27, 28, 29 } }
};
Console.WriteLine("Original array:");
PrintArray(arr);
int[] flatArr = new int[arr.Length];
int index = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
for (int k = 0; k < arr.GetLength(2); k++)
{
flatArr[index++] = arr[i, j, k];
}
}
}
Array.Sort(flatArr);
index = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
for (int k = 0; k < arr.GetLength(2); k++)
{
arr[i, j, k] = flatArr[index++];
}
}
}
Console.WriteLine("Sorted array:");
PrintArray(arr);
}
public static void PrintArray(int[,,] arr)
{
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
for (int k = 0; k < arr.GetLength(2); k++)
{
Console.Write(arr[i, j, k] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
Console.WriteLine();
}
}
//This code is contributed bu Akash Jha
JavaScript
const R = 3, C = 3, H = 3;
function sortfun(arr) {
// One by one sort individual rows.
for (let i = 0; i < H; i++)
for (let j = 0; j < R; j++)
arr[i][j].sort();
// Printing the sorted matrix
for (let i = 0; i < H; i++) {
console.log(`Layer ${i + 1}:`);
for (let j = 0; j < R; j++) {
console.log(arr[i][j].join(' '));
}
}
}
let arr = [ [ [3, 2, 1],
[6, 5, 4],
[9, 8, 7]
],
[ [11, 12, 13],
[14, 15, 16],
[17, 18, 19]
],
[ [21, 22, 23],
[24, 25, 26],
[27, 28, 29]
]
];
sortfun(arr);
OutputLayer 1:
1 2 3
4 5 6
7 8 9
Layer 2:
11 12 13
14 15 16
17 18 19
Layer 3:
21 22 23
24 25 26
27 28 29
Similar Reads
How to Sort a Multidimensional Array in JavaScript by Date ? Sorting a Multidimensional Array by date consists of ordering the inner arrays based on the date values. This needs to be done by converting the date representation into the proper comparable formats and then applying the sorting function to sort the array in ascending or descending order. Below are
2 min read
Sort an array having 3 types of Values We are given an array containing three different types of elements, and the task is to sort the array. This problem has been asked in various forms, and in this article, we will explore the three most common forms of this problem.Table of ContentSort an array of 0s, 1s and 2sThree way partitioning a
4 min read
Sort given Array based on the fractional values Given an array arr[] that contains N real numbers. The task is to sort the array in decreasing order of the Fractional Values Note: If the values of the fractional part are same then sort those elements in Decreasing order of their Integer Values. Examples: Input: arr[] = { 8.33, -3.85, 1.999, 6.33,
10 min read
How to Sort an Array in Scala? Sorting arrays effectively is essential for many applications, regardless of whether you're working with texts, custom objects, or numerical data. Because Scala is a strong and expressive language, it provides a variety of array sorting methods that may be customized to fit various needs and situati
5 min read
Sorting a Hashmap according to values Given the marks scored out of 100 by a student in subjects where the name of the subject is key and marks scored is the value. A HashMap is created using the subject name and respective marks as key-value pairs. The task is to sort the HashMap according to values i.e. according to marks.Example: Inp
9 min read