我的问题是这样的:给定一个矩阵,根据它的行和按升序排序。 也就是说,如果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
第1行的和是14
,a
第2行的和是18
,a
第3行的和是26
。 因此,b
的第1行将是a
的第3行,b
的第2行将是a
的第2行,b
的第3行将是A的第1行。
我在寻找一个算法,而不是内置功能。
简单的方法(但也是效率较低的)是使用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
应该变成max