如何在C ++中按矩阵的降序对矩阵进行降序排序

时间:2020-06-13 12:45:52

标签: c++ algorithm matrix

我的问题是:给定矩阵,根据其行的总和以升序对其进行排序。也就是说,如果A是以下矩阵:

A = [2, 5, 6, 1]
    [8, 2, 5, 3]
    [9, 7, 4, 6]

因此,我会得到:

B = [9, 7, 4, 6]
    [8, 2, 5, 3]
    [2, 5, 6, 1]

因为A的第一行的总和是14A的第二行的总和是18,而A的第三行的总和26B。因此,A的第一行将是B的第三行,A的第二行将是B的第二行,{的第三行{1}}将是A的第一行。

我正在寻找一种算法,而不是内置函数。

1 个答案:

答案 0 :(得分:0)

简单的方法(但效率也较低)是使用init { post { currentItem = 0 } } fun setCurrentPage(position: Int) { post { setCurrentItem(position, true) // I want smooth scroll } } ,所以您将较小的对象放在第一个位置,然后将第二个较小的对象放在第二个位置,等等:

selection sort

如果您需要另一节经文,则只需从以下内容中进行切换:

#include <iostream>

int sum(const int* array, int size){
    int tot = 0;
    for (int i=0; i<size; i++){
        tot+=array[i];
    }
    return tot;
}
void sort(int** matrix, int n_rows, int n_col){
    for(int i=0; i<n_rows-1; i++)
    {
        int min=i;
        for(int j=i+1; j<n_rows; j++)
            if (sum(matrix[j],n_col) > sum(matrix[min], n_col))
                min= j;
        auto temp=matrix[min];
        matrix[min]=matrix[i];
        matrix[i]=temp;
    }
}
// 2 5 6 1 8 2 5 3 9 7 4 6
int main(){
    int** array = new int*[3];
    for(int i = 0; i < 3; i++){
        int* tmp = new int[4];
        for(int j = 0; j < 4; j++){
            std::cin >> tmp[j];
        }
        array[i] = tmp;
    }
    sort(array,3,4);
    for(int i = 0; i < 3; i++) {
        std::cout << '[';
        for (int j = 0; j < 4; j++)
            std::cout << array[i][j];

        std::cout << ']' << std::endl;
    }
}

if (sum(matrix[j],n_col) > sum(matrix[min], n_col))

也许更改一些变量名,例如if (sum(matrix[j],n_col) < sum(matrix[min], n_col)) 应该变成min