Languages
[Edit]
EN

Java - how to sort 2D array?

5 points
Created by:
Kate_C
19800

Using Java it is possible to sort 2D array in following way.

1. Index transformation example

package com.dirask.example;

public class Program {

    public static void main(String[] args) {
        int[][] array = {
            { 5,  3,  1 },
            { 8, -2,  0 },
            { 3,  7,  6 },
            { 9,  9, -3 }
        };

        // bubble sort example
        for (int i = 0; i < 4 * 3; ++i) {
            for (int j = 0; j < 4 * 3; ++j) {
                int a = array[i / 3][i % 3];
                int b = array[j / 3][j % 3];

                if(a < b) {
                    array[i / 3][i % 3] = b;
                    array[j / 3][j % 3] = a;
                }
            }
        }

        for (int i = 0; i < 4; ++i) {
            for (int j = 0; j < 3; ++j) {
                System.out.print(" " + array[i][j]);
            }
        }
    }
}

Output:

 -3 -2 0 1 3 3 5 6 7 8 9 9

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join