-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 :)

5
  • 1
    What are letter1 and letter2 in the compare(...) method? Commented Apr 9, 2012 at 15:43
  • possible duplicate of How do i sort a simple integer 2 dimensional array? Commented Apr 9, 2012 at 15:43
  • Probably a typo. His original application is likely sorting arrays of characters. Commented Apr 9, 2012 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 Commented Apr 9, 2012 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. Commented Apr 9, 2012 at 15:47

1 Answer 1

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

2 Comments

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.
Yes, the sorting was just fine :-)

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.