我用C写的选择排序算法正确吗?

我用C写的选择排序算法正确吗?,c,algorithm,sorting,selection-sort,C,Algorithm,Sorting,Selection Sort,我书中的一个问题用三行解释了选择排序,然后要求读者用C语言为其编写代码。我在这里编写了代码,它运行良好,但我有点困惑我是否以正确的方式编写了它。请阅读代码,我甚至添加了注释,如果需要请更正 #include <stdio.h> #define VALUESIZE 10 int main(void) { int temp; int value[VALUESIZE] = {3, 5, 46, 89, 72, 42, 31

我书中的一个问题用三行解释了选择排序,然后要求读者用C语言为其编写代码。我在这里编写了代码,它运行良好,但我有点困惑我是否以正确的方式编写了它。请阅读代码,我甚至添加了注释,如果需要请更正

    #include <stdio.h>

    #define VALUESIZE 10

    int main(void)
    {
        int temp;
        int value[VALUESIZE] = {3, 5, 46, 89, 72, 42, 312, 465812, 758, 1};

// Printing array just for the user to see.
        for (int k=0; k<VALUESIZE; k++)
        {
        printf("[");
        printf("%d", value[k]);
        printf("] ");
        }
        printf("\n");

// Sorting algo begins
for (int i=0; i < VALUESIZE - 1; i++) // This will obviously loop through each element in our array except the last element as it will automatically be sorted after n-1 steps
{
    for (int j= i+1; j <= VALUESIZE; j++) // This nested loop will go through each element which appears after ith element. For e.g. If i = 2, then j will loop through entire array starting from j = 3
    {
        if (value[i] > value[j])  // This basic if statement will compare our ith and following jth value
        {
            temp = value[i];      // If the program finds any value[j] greater than value[i], then the values will be swapped.
            value[i] = value[j];
            value[j]  = temp;
        }
    }
}
// Now after sorting, print the new sorted array.
for (int l=0; l<VALUESIZE; l++)
{
    printf("[");
    printf("%d", value[l]);
    printf("] ");
}
printf("\n");
#包括
#定义值大小10
内部主(空)
{
内部温度;
int值[VALUESIZE]={3,5,46,89,72,42,312,465812,758,1};
//打印阵列供用户查看。

对于(int k=0;k选择排序需要遍历数组以比较第i个值。在这一过程结束时,它将交换2个值。这就是为什么它不是一个非常好的排序算法用于中型或大型数组的原因

我在下面稍微修改了你的代码

未经测试但应有效:

// Sorting algo begins
for (int i = 0; i < arr_length - 1; i++)
{
    int min = i;
    for (int j = i + 1; j <= arr_length; j++) 
    {
        if (value[j] < value[min])
        {
            min = j;
        }
    }
    //now swap
    int cache = value[min];
    value[min] = value[i];
    value[i] = cache;
}
//排序算法开始
对于(int i=0;i对于(int j=i+1;j什么让你怀疑?我明白你的意思了。你说先检查第i个元素和第j个元素,然后交换。虽然我对交换元素感到困惑,但我会使用我的原始代码。顺便说一下。没问题,祝你好运。要理解交换,只需关注内部和外部循环,如果你一步一步地过去。