简体   繁体   中英

Sort 2D Array to one column in ascending order

I made this code for sorting the 2D array. I have to check on "duplicates" and "one empty column", but don't know which method to use

example:

 1 2 3
 1 4
 3 2
 3 3 5

result:

 3 2 
 3 3 5 
 1 2 3 
 1 4 
    public int[][] arrSort(int[][] arr) {
        Arrays.sort(arr, (obj1, obj2) -> {
                if (obj1.length == 0) { return 1; }       
                if (obj2.length == 0) { return -1; }        
                int min = Math.min(obj1.length, obj2.length); 
                for (int i = 0; i < min ; i++) {
                   if (obj1[i] != obj2[i]) {                 
                        return obj2[i] - obj1[i];             
                    }  
                }
               return 1;                                
            }); 
      return arr;}}

I have managed to fix the code for you, and I also added some comments for you to use and understand.

EDIT

I fixed the answer with better code and more edge cases.

private static int[][] sort(int[][] arr) {
        Arrays.sort(arr, (obj1, obj2) -> {
            if(obj1.length == 0) return 1; // Make the first array go backwards if it has no items
            if(obj2.length == 0) return -1; // Make the second array go backwards if it has no items

            if(obj1.length > obj2.length) return -1;
            if(obj2.length > obj1.length) return 1;


            int score1 = 0, score2 = 0;
            for (int i = 0; i < obj1.length; i++) {
                if(obj1[i] > obj2[i])
                    score1++;
                else if(obj2[i] > obj1[i])
                    score2++;
            }

            // Make the result negative
            return -Integer.compare(score1, score2);
        });
        return arr;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM