c - 选择排序功能工作排序不正确
问题描述
我正在尝试在 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],对一些数字进行排序,而不对其他数字进行排序。
提前致谢!
解决方案
在选择排序中,内部for
循环的目标是在未排序的子数组中找到最小元素的索引(即从 index 开始到 indexi
结束的数组n-1
)。找到最小值后应进行交换,以便将其正确放置在i
数组中的索引处:
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");
}
推荐阅读
- asp.net-mvc - 输入键上的 Textarea 换行在 .NET Core MVC 应用程序上不起作用
- php - PHP Memcache/Memcached 的 addServer 方法是如何工作的?
- node.js - Neo4j 密码中无法识别我的参数映射
- java - 如何使用 JavaMail 的 MimeUtility 或 Apache Commons 和quoted-printable 获得 UTF-8 字符的两序列表示?
- android - Android Studio 突然在某些文件上显示错误的编码错误
- paperjs - The method Path.Line.translate() does not update the segments of the path
- r - Tabulate column containing list in R
- java - Multithreading Issue with group chat in Java Sockets
- c# - Connect to Oracle Database in C#
- css - flexbox css可以用来创建垂直和水平页面覆盖消息吗