【发布时间】:2021-09-01 17:32:04
【问题描述】:
我正在尝试在 C 中实现我的第一个排序算法,其中一个数字数组作为命令行参数给出,然后调用函数对数组进行排序并打印输出。该程序在排序之前重新打印数组,据我所知,错误在于排序算法本身。这是函数:
void ascending(int n, int arr[])
{
for (int i = 0; i < (n - 1); i++)
{
//min is equal to i (use as index)
int min = i;
//Compare arr[i] to all other elements in the array
for (int j = i + 1; j < n; j++)
{
//If a smaller number is found, its index (j) is now min
if (arr[j] < arr[min])
{
min = j;
//Swapping values to be in correct place
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}
printf("sorted: ");
for (int i = 0; i < n; i++)
{
printf("%i, ", arr[i]);
}
printf("\n");
}
如果我要求它对 [5, 4, 60, 2, 1] 进行排序,它会正确地将输出排序为 sorted: [1, 2, 4, 5, 60]
但如果我要求它对 [60, 5, 3, 3, 1, 4, 2] 进行排序,它将打印:[2, 1, 4, 3, 3, 5, 60],对一些数字进行排序,但不是其他人。
提前致谢!
【问题讨论】:
-
发现程序不起作用后你做了什么?然后你继续调试它吗?在调试器中运行您的程序,并在运行时跟踪其流程和变量值。如果您已经这样做了,请提供您找到的调试信息。 How to debug small programs
标签: c selection-sort