How to Sort a Multidimensional Array by Value (original) (raw)

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,

**Time Complexity: O(N * log N)
**Auxiliary Space: O(1)

**Example:-

C++ `

#include // for std::sort #include

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,

**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

**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.

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)

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);

``

Output

Layer 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