Languages
[Edit]
EN

Java - sort 2D array

5 points
Created by:
Sylvie-Justice
490

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

 

Alternative titles

  1. Java - how to sort 2D array?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - Arrays (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join