+ Reply to Thread
Results 1 to 2 of 2

Thread: sorting two dimensional arrays

  1. #1

    sorting two dimensional arrays

    I have a two dimensional array that is holding the value of 5 cards. The first element of each of the 5 arrays represents the suit of the card, and the second element represents the card value.
    I want to sort the 2d array by the second element, and then by the first element while maintaining the sorted order of the second element (if that makes sense). For example all suits of ones will be lower on the sorted list than all suits of two. So for example, {{0,1},{2,1},{0,2}} should become {{0,1},{2,1},{0,2}}.
    Here is my code :
     int[][] hand = {{3,2},{2,2},{0,1},{1,0},{2,3}};
     public static void sort(int[][] hand){
        Arrays.sort(hand, new Comparator<int[]>(){
            public int compare(int[] o1, int[] o2){
                return Integer.valueOf(o1[1]).compareTo(Integer.valueOf(o2[1]));
    The Output :
    Can anyone give me a hint , why am i getting this ?

  2. #2
    Junior Member
    Join Date
    Feb 2012
    You have to modify your comparator as follows:
    Arrays.sort(hand, new Comparator<int[]>() {
      public int compare(int[] o1, int[] o2) {
        if (o1[0] == o2[0]) {
          return Integer.compare(o1[1], o2[1]);
        } else {
          return Integer.compare(o1[0], o2[0]);
    It will Work.

+ Reply to Thread

Tags for this Thread


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts