gpt4 book ai didi

c++ - 无法将数组传递给排序函数(需要对列而不是行进行排序)

转载 作者:太空宇宙 更新时间:2023-11-04 12:36:03 26 4
gpt4 key购买 nike

我需要使用选择排序对二维数组进行排序。问题是我需要对数组的列而不是行进行排序。下面是我如何分配一个二维数组(以显示结构):

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

关于如何做到这一点有什么想法吗?现在我转置矩阵两次,在转置之间对它进行排序,但我认为这不是一个好的选择,因为它很慢。

最佳答案

您可以将您的函数模板化为具有 int 的 getter:

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);

关于c++ - 无法将数组传递给排序函数(需要对列而不是行进行排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56328983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com