简体   繁体   中英

Sorting 2d array row and column wize

public static boolean  absoluteSorted(int[][] mat) {

    for (int i = 0; i < mat.length; i++) {
        for (int j = 0; j < mat[i].length; j++) {
            if(mat[i][j]<mat[mat.length-1][mat[i].length-1]) {
                return true;
            }
        }
    }
    return false;
}

what is wrong with my code??

Example:
Input: Output:false Input: -5 0 5 Output:true 2 0 0 -2 9 12 8 6 0 9 10 20 4 5 8

what is wrong with my code?

If you want to check that the columns and rows are sorted, you need to compare all element with the next one in its column and the next one in its row.

Your code is comparing against the last element in each row and column.

Also, your code returns true on the first element that is "in order". It should only return when it has checked all elements that need checking.

My guess is that this line:

if(mat[i][j]<mat[mat.length-1][mat[i].length-1]) {

Should be something like:

if(mat[i][j] < mat[i-1][j-1]) { // Except when i or j == 0

Because "sorting" means comparing each cell in turn.

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