2d阵列多个运动选择排序

时间:2014-09-11 04:22:49

标签: java arrays sorting multidimensional-array bubble-sort

我正在尝试编写一个方法,对2d数组的每隔一行中的项进行排序(使用冒泡排序)。当在第一行中发生移动时,我希望紧接在被排序的行下面的行中的类别编号也移动。冒泡排序对于数组的前半部分正常工作,但随后在数组中途停止,并且下面的行的移动不会正确发生。

for(int i = 0; i<differencearray.length; i= i+2){ //skips every other row
        for(int j = 0; j<differencearray[i].length; j++){
            for(int l = 0; l<differencearray[i].length-1; l++){
                if(differencearray[j][l]>differencearray[j][l+1]){
                    int temp = differencearray[j][l]; //moves row being sorted
                    differencearray[j][l] = differencearray[j][l+1];
                    differencearray[j][l+1] = temp;
                    int temp1 = differencearray[i+1][j]; //moves row immediately below what is being sorted
                    differencearray[i+1][j] = differencearray[i+1][l];
                    differencearray[i+1][l] = temp1;
                }
            }
        }
    }

预期产出:

9 13 15 24 2147483647

3 4 2 5 1

15 16 17 18 2147483647

1 4 5 3 2

9 12 18 27 2147483647

1 4 2 5 3

12 13 16 25 2147483647

3 1 2 5 4

17 24 25 27 2147483647

2 1 4 3 5

实际输出:

9 13 15 24 2147483647

1 2 3 4 5

15 16 17 18 2147483647

1 2 3 4 5

9 12 18 27 2147483647

1 4 3 2 5

13 16 12 2147483647 25

1 4 2 3 5

24 17 27 25 2147483647

2 4 3 1 5

知道我做错了什么?提前谢谢!

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助。

import java.util.Arrays;


public class BloodySort {

    public static void main(String[] args) {
        int[][] differencearray = {
                {9, 13, 15, 2},
                {1, 2, 3, 4},
                {9, 13, 15, 2, 17, 29, 31, 88, 56, 5, 4},
                {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
        };

        for(int i = 0; i<differencearray.length; i= i+2){ //skips every other row
            for(int j = 0; j<differencearray[i].length-1; j++){
                for(int l = j+1; l<differencearray[i].length; l++){
                    if(differencearray[i][j]>differencearray[i][l]){
                        int temp = differencearray[i][j]; //moves row being sorted
                        differencearray[i][j] = differencearray[i][l];
                        differencearray[i][l] = temp;

                        int temp1 = differencearray[i+1][j]; //moves row immediately below what is being sorted
                        differencearray[i+1][j] = differencearray[i+1][l];
                        differencearray[i+1][l] = temp1;
                    }
                }
            }
        }

        for ( int i = 0; i < differencearray.length; ++i ) {
            System.out.println( Arrays.toString(differencearray[i]) );
        }
    }
}

它给出了以下(我认为是正确的)答案。

[2, 9, 13, 15]
[4, 1, 2, 3]
[2, 4, 5, 9, 13, 15, 17, 29, 31, 56, 88]
[4, 11, 10, 1, 2, 3, 5, 6, 7, 9, 8]