用C ++对对齐排列二维数组

时间:2016-06-01 17:57:00

标签: c++ arrays sorting bubble-sort

我有一个需要对角排序的二维数组,例如

1  2  4  7
3  5  8  11
6  9  12 14
10 13 15 16

我设法创建了一个新的一维数组,其中包含二维数组的元素并对其进行冒泡排序。我被困在如何用排序的一维数组对角填充二维数组。 有什么帮助吗?

原始数组的行和列不一定相等,但在对角排序的数组中,我认为应该是这样。

//Function that swaps two values (used in bubble sort)
void swap(int &a, int &b){
    int hold = a;
    a = b;
    b = hold;
}

//Function that bubble sorts a one dimensional array
void bubbleSort(int a[], int r){
    for (int pass = 1; pass < r; pass++){
        for (int i = 0; i < r - 1; i++){
            if (a[i + 1] < a[i]){
                //Swap a[i] and a[i + 1]
                swap(a[i + 1], a[i]);
            }
        }
    }
}

//Function that diagonally sorts a two dimensional array
void diagonalSort(int array[][column], int row){

    //Step 1: Store the two dimensional array in a one dimensional array
    int flatSize = row*column, *flat = new int[flatSize], a = 0;
    for (int b = 0; b < row; b++){
        for (int c = 0; c < column; c++){
            flat[a] = array[b][c];
            a++;
        }
    }

    //Step 2: Bubble sort the one dimensional array that was created
    bubbleSort(flat, flatSize);

    //Step 3: ??
}

0 个答案:

没有答案