2

我需要在 C 中实现 Shell 排序并使用优化版本(首先将间隙设置为 array/2 的大小,然后将该数字重复除以 2.2)。问题是答案并不总是完全排序,我不确定这是因为我的代码中的一些逻辑错误还是 Shell 排序的一些缺点。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX 7

void shellSort(int *a, int size);
void insert(int *a, int next_pos, int gap);

void shellSort(int *a,int size)
{
    int gap = floor(size/2);
    int next_pos;
    while (gap>0)
    {
        for(next_pos = gap; next_pos < size; next_pos++)
            insert(a, next_pos, gap);

        if(gap == 2)
            gap = 1;
        else
            gap = (int)(gap/2.2);
    }
}

void insert(int *a, int next_pos, int gap)
{
    int value = a[next_pos];
    while(next_pos >= gap && a[next_pos] < a[next_pos-gap])
    {
        a[next_pos] = a[next_pos-gap];
        next_pos = next_pos - gap;
    }
    a[next_pos] = value;
}

int main()
{
    int nums[MAX];
    time_t t;
    srand((unsigned) time(&t)); // seed randomiser

    printf("Array before sorting:\n");
    int i;
    for(i=0; i<MAX; i++)
    {
        nums[i] = rand() % 101; // filling array with random numbers
        printf("%d\t", nums[i]);
    }

    shellSort(nums, MAX);

    printf("\nArray after sorting:\n");
    for(i=0; i<MAX; i++)
        printf("%d\t", nums[i]);

    return 0;
}

以下是我的输出:

Array before sorting:
74  26  1   12  38  81  94  
Array after sorting:
12  1   26  38  74  81  94  

编辑:在我完成我的问题之前发布

4

1 回答 1

5

我认为你的问题出在这里:

 int value = a[next_pos];
 while(next_pos >= gap && a[next_pos] < a[next_pos-gap])

由于您在next_pos下面的行中进行了更改,我认为这些行应该阅读(如果我对 shellsort 的理解是正确的):

 int value = a[next_pos];
 while(next_pos >= gap && value < a[next_pos-gap])
于 2016-04-16T08:12:41.120 回答