简体   繁体   English

在2D数组中的行中对元素进行排序

[英]sorting elements in a row in a 2D array

I have to sort elements in each row and then display the array. 我必须对每一行中的元素进行排序,然后显示数组。

For example, if the input array is: 例如,如果输入数组为:

             5 1 3                  1 3 5
   INPUT:    7 6 4        OUTPUT:   4 6 7
             9 8 2                  2 8 9

My code for that was: 我的代码是:

for (int i = 0; i < size; i++) { //"size" is the size of the square matrix 
    for (int j = 0; j < size; j++) {
        for (int k = 0; k < size - 1; k++) {
            for (int l = 0; l < size - k - 1; l++) {
                if (arr[i][j] > arr[i][j+1]) { //arr[][] is of datatype int
                    int temp = arr[i][j];
                    arr[i][j] = arr[i][j+1];
                    arr[i][j+1] = temp;
                }
            }
        }
    }
}

Any suggestions? 有什么建议么?

for (int i = 0; i < size; i++){ //"size" is the size of the square matrix 
    for (int j = 0; j < size; j++){
        for (int k = j+1; k < size; k++){
           if (arr[i][j] > arr[i][k]){ //arr[][] is of datatype int
                  int temp  =  arr[i][j];
                  arr[i][j] =  arr[i][k];
                  arr[i][k] =  temp;
            }

         }
     }
}

I don't think you need 4th loop 我不认为你需要第四循环

I would do it simpler 我会做得更简单

    for(int[] r : arr){
        Arrays.sort(r);
    }

I would create a method to sort rows, and then just iterate through the rows in the matrix and sort them one at a time. 我将创建一种对行进行排序的方法,然后遍历矩阵中的行并一次对其进行排序。 For example: 例如:

public static int[] sortRow(int[] row) // selection sort
{
    for (int i = 0; i < row.length - 1; i++) {
        for (int j = i + 1; j < row.length; j++) {
            if (row[i] > row[j]) {
                int temp = row[i];
                row[i] = row[j];
                row[j] = temp;
            }
        }
    }
    return row;
}

public static void main(String args[]) 
{
    int[][] arr = {{5, 1, 3}, {7,6,4}, {9,8,2}};

    for (int r = 0; r < arr.length; r++) { // for every row in the matrix
        arr[r] = sortRow(arr[r]); // set the row to be the sorted row
    }

    // print out the array to the console
    for (int r[] : arr) {
        for (int c : r)
            System.out.print(c + " ");
        System.out.println();
    }
}

Output: 输出:

1 3 5 
4 6 7 
2 8 9 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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