无法将数组传递给排序函数(需要对列而不是行进行排序)
Can't pass array to a sorting function(need to sort columns, not rows)
我需要使用选择排序对二维数组进行排序。问题是我需要对数组的列而不是行进行排序。
这是我如何分配一个二维数组(以显示结构):
int** array = new int*[rows];
for (int i = 0; i < rows; i++) {
array[i] = new int[columns];
}
然后我在其中添加一些项目。这是我的排序函数:
void selectionSort(int* arr, int n)
{
int i, j, min_idx;
for (i = 0; i < n; i++)
{
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}
我没有指定交换,因为它不言自明。
因此,我再次需要对矩阵的每一列进行排序。例如:
输入:
5 3 1
2 0 9
4 2 6
输出:
2 0 1
4 2 6
5 3 9
关于如何做到这一点有什么想法吗?现在我转置矩阵两次,在转置之间我对它进行排序,但我认为这不是一个好的选择,因为它很慢。
您可以将您的函数模板化为具有 getter 的 int:
template <typename F>
void selectionSort(F f, int size)
{
for (int i = 0; i < size; i++)
{
int min_idx = i;
for (int j = i + 1; j < size; j++)
if (f(j) < f(min_idx))
min_idx = j;
swap(f(min_idx), f(i));
}
}
因此,在一维空间中,您有旧的:
selectionSort([arr](int i) -> int&{ return arr[i]; }, n);
以及列:
selectionSort([arr, j](int i) -> int&{ return arr[i][j]; }, n);
我需要使用选择排序对二维数组进行排序。问题是我需要对数组的列而不是行进行排序。 这是我如何分配一个二维数组(以显示结构):
int** array = new int*[rows];
for (int i = 0; i < rows; i++) {
array[i] = new int[columns];
}
然后我在其中添加一些项目。这是我的排序函数:
void selectionSort(int* arr, int n)
{
int i, j, min_idx;
for (i = 0; i < n; i++)
{
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}
我没有指定交换,因为它不言自明。
因此,我再次需要对矩阵的每一列进行排序。例如:
输入:
5 3 1
2 0 9
4 2 6
输出:
2 0 1
4 2 6
5 3 9
关于如何做到这一点有什么想法吗?现在我转置矩阵两次,在转置之间我对它进行排序,但我认为这不是一个好的选择,因为它很慢。
您可以将您的函数模板化为具有 getter 的 int:
template <typename F>
void selectionSort(F f, int size)
{
for (int i = 0; i < size; i++)
{
int min_idx = i;
for (int j = i + 1; j < size; j++)
if (f(j) < f(min_idx))
min_idx = j;
swap(f(min_idx), f(i));
}
}
因此,在一维空间中,您有旧的:
selectionSort([arr](int i) -> int&{ return arr[i]; }, n);
以及列:
selectionSort([arr, j](int i) -> int&{ return arr[i][j]; }, n);