在2D数组中连续排序元素

时间:2013-12-28 07:21:21

标签: java arrays sorting

我必须对每行中的元素进行排序,然后显示数组。

例如,如果输入数组是:

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

我的代码是:

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;
                }
            }
        }
    }
}

有什么建议吗?

3 个答案:

答案 0 :(得分:5)

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;
            }

         }
     }
}

我认为你不需要第4次循环

答案 1 :(得分:4)

我会做得更简单

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

答案 2 :(得分:0)

我会创建一个方法来对行进行排序,然后只迭代矩阵中的行并一次对它们进行排序。例如:

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();
    }
}

输出:

1 3 5 
4 6 7 
2 8 9