先取一个小于n的整数d1作为第一个增量,把文件的全部记录分成d1个组。所有距离为d1的倍数的记录放在同一个组中。先在各组内进行直接插入排序;然后,取第二个增量d2<d1重复上述的分组和排序,直至所取的增量dt=1(dt<dt-l<…<d2<d1),即所有记录放在同一组中进行直接插入排序为止。
排序结果如下:
data before sort: 32 20 84 34 88 30 16 26 4 23
data after sort: 4 16 20 23 26 30 32 34 84 88
Java代码:
排序结果如下:
data before sort: 74 99 8 36 86 37 59 45 42 90
更多信息请参考:http://baike.baidu.com/view/178698.htm
C语言代码:
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <time.h>
void init(int *array, int count)
{
int n = 0;
srand((unsigned int)time(NULL));
for (n=0; n<count; n++)
{
array[n] = rand()%100 + 1;
}
}
void output(int *array, int count)
{
int n = 0;
for (n=0; n<count; n++)
{
printf("%5d", array[n]);
}
printf("\n");
}
void shellsort(int *array,int count)
{
int i = 0;
int j = 0;
int t = 0;
int k = count/2;
while(k>0)
{
for(i = k;i< count;i++)
{
t = array[i];
j = i;
while(j >= k && t < array[j - k])
{
array[j] = array[j-k];
j = j-k;
}
array[j] = t;
}
k /= 2;
}
}
int main()
{
const int count = 10;
int array[count];
memset(array, 0, sizeof(int)*count);
init(array, count);
printf("data before sort: ");
output(array, count);
shellsort(array, count);
printf("data after sort: ");
output(array, count);
return 0;
}
排序结果如下:
data before sort: 32 20 84 34 88 30 16 26 4 23
data after sort: 4 16 20 23 26 30 32 34 84 88
Java代码:
import java.util.Random;
/**
* 先取一个小于n的整数d1作为第一个增量,把文件的全部记录分成d1个组。
* 所有距离为d1的倍数的记录放在同一个组中。先在各组内进行直接插入排序;
* 然后,取第二个增量d2<d1重复上述的分组和排序,直至所取的增量dt=1(dt<dt-l<…<d2<d1),
* 即所有记录放在同一组中进行直接插入排序为止。
*/
public class Sort
{
/*
* 输出数组中的数据
*/
public static void OutputArray(int[] array)
{
for (int data : array)
{
System.out.print(data + "\t");
}
System.out.println();
}
/*
* 生成需要排序的数组
*/
public static int[] createArray(int count)
{
int array[] = new int[count];
Random r = new Random();
for (int i = 0; i < count; i++)
{
array[i] = r.nextInt(100);
}
System.out.println("");
System.out.print("data before sort:\t");
OutputArray(array);
return array;
}
public static void ShellSort(int[] array)
{
int n = array.length;
int k = n/2;
while(k>0)
{
for(int i = k; i< n; i++)
{
int t = array[i];
int j = i;
while(j >= k && t < array[j - k])
{
array[j] = array[j-k];
j = j-k;
}
array[j] = t;
}
k /= 2;
}
}
public static void main(String[] args)
{
int[] arr1=createArray(10);
System.out.print("data after sort:\t");
ShellSort(arr1);
OutputArray(arr1);
}
}
排序结果如下:
data before sort: 74 99 8 36 86 37 59 45 42 90
data after sort: 8 36 37 42 45 59 74 86 90 99