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]进行排序,它将正确地对输出进行排序:[1,2,4,5,60]

但如果我让它排序[60,5,3,3,1,4,2],它会打印:[2,1,3,5,60],排序一些数字,但不排序其他数字。

提前感谢!

在选择排序中,内部for循环的目标是找到未排序子数组中最小元素的索引(即,从索引i开始到索引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");
}

在此if语句中

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

分配后

min = j;

这个交换

//Swapping values to be in correct place
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;

没有道理。

内部for循环可以用以下方式写入

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;
}
}
if ( min != i )
{   
//Swapping values to be in correct place
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}

请注意,最好按照第一个参数指定数组,第二个参数指定阵列中的数字元素的方式声明函数

例如

void ascending( int arr[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
size_t min = i;
for ( size_t j = i + 1; j < n; j++ )
{
if ( arr[j] < arr[min] ) min = j;
}
if ( min != i )
{
int tmp = arr[i];
arr[i] = arr[min];
arr[min] = tmp;
}
}
}