我正在尝试对矩阵进行排序,但我的代码似乎过长、复杂且效率低下。 我确信有更好、更有效的方法来对矩阵进行排序,但尽管我努力尝试,但我找不到它们。如果有人可以帮助我,我将非常感激
我尝试初始化一个数组
temp
将矩阵中的每个元素复制到其中,然后对数组进行排序(冒泡排序),然后将排序后的数组复制回矩阵。这个过程比我想象的要长。
int main()
{
// Matrix initialization
int matrix[row][col];
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
cin >> matrix[i][j];
// Building an array and copying the matrix elements to the array
int temp[row* col];
int nextRow = 0;
for (int i = 0; i <= row* col; i++)
{
if (i - (col* nextRow) < row)
temp[i] = matrix[nextRow][i - (col* nextRow)];
else if (i - (col* nextRow) == row)
{
i--;
nextRow++;
}
}
//Bubble sorting the array
for (int i = 0; i + 1 < row * col; ++i)
{
for (int j = 0; j + 1 < (row * col) - i; ++j)
{
if (temp[j] > temp[j + 1])
{
int t = temp[j];
temp[j] = temp[j + 1];
temp[j + 1] = t;
}
}
}
//Copying back the elements from the array to the matrix
nextRow = 0;
for (int i = 0; i < row * col; ++i)
{
if (i % row == 0)
nextRow++;
matrix[nextRow][i - (col * nextRow)] = temp[i];
}
return 0;
}
这是一个使用 std::sort 的示例。
#include <array>
#include <algorithm>
#include <iostream>
int main()
{
// sizes of your matrix
static constexpr std::size_t rows_v{ 5ul };
static constexpr std::size_t cols_v{ 5ul };
// initialize your matrix with values
// I like using std::array (easier to pass around to functions)
//int matrix[rows_v][cols_v] // you can still use "C" style array, but I use std::array
std::array<std::array<int, cols_v>, rows_v> matrix{{ // remove one bracket here if you use "C" style array
{1,2,3,4,5},
{9,6,4,3,1},
{6,7,3,2,3},
{9,4,6,2,3},
{3,0,4,2,1}
}};
// range based for loop that will return
// each row of the matrix one by one
// each row will be a reference to a std::array<int, cols_v>
// no need to type that, the compiler can figure out the type for you
for (auto& row : matrix)
{
// sort each row from begin to end.
// std::sort(std::begin(row),std::end(row)); // for "C" style array
std::sort(row.begin(), row.end());
}
// then show the content
// this time by const& since we are only going to output values
// not change them
for (const auto& row : matrix)
{
for (const auto value : row)
{
std::cout << value << " ";
}
std::cout << "\n";
}
return 0;
}