Search code examples
csortingshellsort

Shell sort in C not giving required result


I am required to implement a Shell sort in C and use the optimised version (where the gap is first set to size of array/2 and then this number is repeatedly divided by 2.2). The problem is that the answer isn't always completely sorted and I am not sure whether this is because of some logic error in my code or some shortcoming of the Shell sort.

This is my code:

#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;
}

The following is my output:

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

edit: posted before I was done with my question oops


Solution

  • I think your problem lies here:

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

    Since you're changing next_pos in the lines below, i think those lines should read (if my understanding of shellsort is correct):

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