Table of Content
The following function is a Shell sort for sorting an array of integers. The basic idea of this sorting algorithm, which was invented in 1959 by D. L. Shell.
The shellsort function is from K&R C, added test driver to verify.
#include <stdio.h>
#include <string.h>
void shellsort(int v[], int n);
/* test shellsort function */
main()
{
int v1[9] = {4,5,2,1,45,76,23,12,10};
printf("The original number array: ");
int i;
for (i=0; i<9; i++)
printf(" %d", v1[i]);
printf("\n");
shellsort(v1,9);
printf("The sorted number array: ");
for (i=0; i<9; i++)
printf(" %d", v1[i]);
}
/* shellsort: sort v[0]...v[n-1] into increasing order */
void shellsort(int v[], int n)
{
int gap, i, j, temp;
for (gap = n/2; gap > 0; gap /= 2)
for (i = gap; i < n; i++)
for (j=i-gap; j>=0 && v[j]>v[j+gap]; j-=gap) {
temp = v[j];
v[j] = v[j+gap];
v[j+gap] = temp;
}
}
test result:
$ shellsort The original number array: 4 5 2 1 45 76 23 12 10 The sorted number array: 1 2 4 5 10 12 23 45 76