Languages
[Edit]
EN

Java - how to sort 2D array?

5 points
Created by:
Kate_C
2845

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

 

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍