Suvasish Sarker
Suvasish Sarker

Reputation: 435

How to sort a two dimension array (each row) in Java

To solve a problem i need to sort each row of a two dimension array.

Initial array

35 22 42 28 20 11
35 21 14 33 1  34
35 42 16 22 38  8
29 12 42 25 28  2
25 28 22 11 20 35
1  40 41 43 44 45

After Sort:

11 20 22 28 35 42 
 1 14 21 33 34 35
 8 16 22 35 38 42
 2 12 25 28 29 42
11 20 22 25 28 35
 1 40 41 43 44 45

Followed this docs

Sorting a 2D Integer array based on a column

java Arrays.sort 2d array

all of them suggested to use Comparator.

But i got an impression that it compares its two arguments. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

So couldn't really make it work for my case (6 columns).

Any idea/pointer would be helpful.

After taking the Input this is what i've tried

    Arrays.sort(arr, new Comparator<int[]>() {
        @Override
        public int compare(int[] int1, int[] int2) {
            return Integer.valueOf(int1[0]).compareTo(int2[0]);
        }
    });
    for(c=0;c<6;c++) {
        for(d=0;d<6;d++) {
            System.out.println(arr[c][d]);
        }
        System.out.println();
    }        

and getting this..

35 22 42 28 20 11
35 21 14 33 1 34
35 42 16 22 38 8
29 12 42 25 28 2
25 28 22 11 20 35
1 40 41 43 44 45

1
40
41
43
44
45

25
28
22
11
20
35

29
12
42
25
28
2

35
22
42
28
20
11

35
21
14
33
1
34

35
42
16
22
38
8

Upvotes: 1

Views: 6062

Answers (2)

Masudul
Masudul

Reputation: 21961

For, your case you don't need to implement Comparator. Just iterate horizontal array on 2D array and apply Arrays.sort.

   Integer[][] theArray = 
   {
        { 35, 22, 42, 28, 20, 11 },
        { 35, 21, 14, 33, 1, 34 }
   };

   for (Integer outer[] : theArray) {

       Arrays.sort(outer);

       for (Integer integer : outer) {
           System.out.print(" " + integer);
       }

       System.out.println();
   }

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

A two-dimensional array is in fact an array of arrays. You want each inner array to be sorted. So you just need to loop over these inner arrays and sort them:

int[][] outerArray = ...;
for (int[] innerArray : outerArray) {
    Arrays.sort(innerArray);
}

Upvotes: 3

Related Questions