c - Gasport 或 Shell Sort 无法正确滑动

标签 c sorting

我正在设置一个 GapSort 程序,因为某些数组代码无法正常工作。我错过了什么?

void main()
{
    int eX[10] = {1, 3, 49, 29, 20, 8, 28, 24, 10, 29};
    int eXlen = sizeof(eX) / sizeof(int);
    gapSort(eX, eXlen);
} 
void gapSort(int arr[], int len)
    {
        int temp, gap, swap;
        gap = len / 2;
        while (1)
        {
            for (int i = 0; i < len - gap; i++)
            {
                swap = 0;
                if (arr[i] > arr[i + gap])
                {
                    temp = arr[i];
                    arr[i] = arr[i + gap];
                    arr[i + gap] = temp;
                    swap = 1;
                }
            }
            if (swap == 0)
            {
                if (gap == 1)
                    break;
                gap /= 2;
            }
        }
    }

1, 3, 49, 29, 20, 8, 28, 24, 10, 29 对于这种类型的数组它不起作用

最佳答案

您必须在 for 循环之前放置 swap = 0;

如果您在整个循环中没有交换任何东西,您想更改 gap 值。对于您当前的实现,您可能已经交换了值,例如使用 i=1,但您将在下一个循环中重置 swap=0,因此您将使用相同的 gap 重新迭代,前提是您将值交换为 i 的最后一个值。如果您在 arrDisp 旁边显示 swap 的值,您自己可能已经看到了这个问题。 (我假设 arrDisp 是一个显示数组内容的函数。这个函数调用在它被编辑之前在原始问题中。)

static void gapSort(int arr[], int len)
{
    int temp, gap, swap;
    gap = len / 2;
    while (1)
    {
        swap = 0;
        for (int i = 0; i < len - gap; i++)
        {
            if (arr[i] > arr[i + gap])
            {
                temp = arr[i];
                arr[i] = arr[i + gap];
                arr[i + gap] = temp;
                swap = 1;
            }
        }
        /* arrDisp(arr, len); */
        if (swap == 0)
        {
            if (gap == 1)
                break;
            gap /= 2;
        }
    }
}

关于c - Gasport 或 Shell Sort 无法正确滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495339/

相关文章:

c - 如何循环 <windows.h> system ("color") 命令以使命令提示符快速改变其颜色?

C- 对字符串字符执行数学运算

c - strtoul 从字符串日期 ("03/10/2013 14:01:00") 转换为 time_t

c++ - 使用自定义比较器排序时出现运行时错误

python-3.x - 在Python中对具有多个小数点的字典和字符串中的键进行排序

c - c中的sscanf函数用法

c - GCC的函数指针,分配地址

arrays - 排序算法与完全排序的总比较

sorting - MapReduce 框架如何实现排序阶段?

perl - 如何在不使用 Perl 中的 $b(比较)$a 的情况下对一个键进行升序排序,另一个键进行降序排序?