【问题标题】:My selection sort is very weird (code in C)我的选择排序很奇怪(C 中的代码)
【发布时间】:2020-07-16 14:12:29
【问题描述】:

我的选择排序成功地对某些数字进行排序,但在某些数字上失败。这段代码对我来说似乎很合乎逻辑,我什至一步一步地打印出来,但不知何故它不起作用。

#include <stdio.h>
#include <string.h>

int number[] = {2, 5, 3, 1};
int length;
void sort(void);
void swap(int *xp, int *yp);

int main(void)
{

    length = sizeof(number)/sizeof(number[0]);
    for (int i = 0; i < length; i++)
    {
        printf("%i ", number[i]);   
    }
    printf("\n");
    sort();
}

void sort(void)
{
    //number

    for (int i = 0; i < length - 1; i++)
    {
        
        int max = i;
        //printf("max:%i\n",max);
        for (int j = i + 1; j < length; j++)
        {
            //printf("max:%i and j: %i\n",number[max], number[j]);
            if (number[j] > number[max])
            {
                max = j;

                //SWAP WINNER
                swap(&number[max], &number[i]);
            }
        }
        
        for (int k = 0; k < length; k++)
        {
            printf("%i ", number[k]);
        }
        printf("\n");

    }
    printf("\nnow:\n");
    for (int k = 0; k < length; k++)
    {
        printf("%i ", number[k]);
    }
    printf("\n");
}

void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

结果:

2 5 3 1
3 2 5 1
3 5 2 1
3 5 2 1 

now:
3 5 2 1 ~/ $

无论如何,另一个问题,为什么它必须使用指针?因为没有他们就行不通。有什么建议吗?

【问题讨论】:

  • 你不应该在内部循环中交换。在for(int j=... 循环结束后进行交换。
  • 哇,成功了!你能告诉我其中的逻辑吗?那么第一次交换怎么可能跳过5号跳到3号

标签: c algorithm sorting selection-sort


【解决方案1】:

错误在此块中:

        if (number[j] > number[max])
        {
            max = j;

            //SWAP WINNER
            swap(&number[max], &number[i]);
        }

max = j 之后,max 是迄今为止发现的最大数字的索引。但是,您将该数字与i 处的数字交换,因此max 不再引用最大数字。

【讨论】:

    【解决方案2】:

    选择排序是一种相当简单的算法,您使用单独的变量来跟踪最大值的索引是不必要的复杂化。

    我的建议:

    • 移除 max 变量。
    • 从最后一个索引开始外循环,然后将其递减到第一个,这样索引 i 将始终指向子数组中的最后一个索引,即放置最大编号的索引。
    • 从第一个索引到 i-1 运行内部循环。

    进行这些更改后,在内循环中比较 array[i] 和 array[j],如果 array[j] 更大则交换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多