1

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
1
  • 1
    Do you need to do this in place (as a problem or assignment) or is this a practical problem you're encountering with access to any arbitrary data structures? Commented Nov 16, 2013 at 14:53

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.