首页 > 解决方案 > 选择排序功能工作排序不正确

问题描述

我正在尝试在 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],对一些数字进行排序,而不对其他数字进行排序。

提前致谢!

标签: cselection-sort

解决方案


选择排序中,内部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");
}

推荐阅读