-1

I'm using Java and I have an int[][] array like so:

[ 65][  4]  
[108][ 47]  
[ 32][279]  
[103][ 26]  
[111][138]  
[100][ 63]  
[112][ 33] ...etc.

And I need to sort from least to greatest, based on the second column's values. I tried this code, also found on this website:

    print(myArray);
    System.out.println("==========");

    Arrays.sort(myArray, new Comparator<int[]>() {
        @Override
        public int compare(int[] int1, int[] int2)
        {
            Integer number1 = int1[1];
            Integer number2 = int2[1];
            return number1.compareTo(number2);
        }
    });

    print(myArray);

Where my print method is as follows:

public static void print(int[][] array) {
    int k = 0;
    while (array[k][0] != 0) {
        System.out.println("[" + array[k][0] + "][" + array[k][1] + "]");
        k++;
    }
}

It just doesn't seem to print the second time, no matter what. I'm just not sure what I'm doing wrong here. Hopefully it's just an easy fix :)

Sam032789
  • 1
  • 1
  • 2
  • 1
    What are `letter1` and `letter2` in the `compare(...)` method? – Sergey Kalinichenko Apr 09 '12 at 15:43
  • possible duplicate of [How do i sort a simple integer 2 dimensional array?](http://stackoverflow.com/questions/7908307/how-do-i-sort-a-simple-integer-2-dimensional-array) – Brian Roach Apr 09 '12 at 15:43
  • Probably a typo. His original application is likely sorting arrays of characters. – Alain Apr 09 '12 at 15:43
  • How did you try the supplied code if there is no way it compiles ? letter1 and letter2 are not really in scope. I think you want number1 and number2 – imichaelmiers Apr 09 '12 at 15:43
  • fixed the letter/number thing. Sorry about that. Alain is right, it's actually sorting an array of characters. The second column is the number of occurrences in the text file. – Sam032789 Apr 09 '12 at 15:47

1 Answers1

2

It seems like your print method is bad (or your supplied code is not enough to reproduce your error). Your code prints the first time, but then hits an ArrayIndexOutOfBoundsException (which you should get too, if this is the actual issue).

Try this print method instead, it works for me.

public static void print(int[][] array) {
    for (int i = 0; i < array.length; i++) {
        System.out.println("[" + array[i][0] + "][" + array[i][1] + "]");
    }
}
Paaske
  • 4,345
  • 1
  • 21
  • 33
  • Ah, I was wondering if it was my print method. You see, the problem is that at the time of the array implementation, I'm not to know the amount of characters in the text. So I end up with a bunch of [0][0]'s in there too. I guess now I know the sorting works. – Sam032789 Apr 09 '12 at 16:00
  • Yes, the sorting was just fine :-) – Paaske Apr 09 '12 at 16:02