希尔排序实际上是一种分组插入排序
基本思想:
先取一个小于n的整数dt作为第一个增量,把文件的全部记录分组。所有距离为dt的倍数的记录放在同一个组中。先在各组内进行【直接插入排序】;然后,取第二个增量d2<dt重复上述的分组和排序,直至所取的增量dt=1,即所有记录放在同一组中进行直接插入排序为止。
比较相隔较远距离(增量)的数,使得数移动时能跨过多个元素,则进行一次比较就可能消除多个元素交换。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WillTest
{
/**
* 希尔排序
* 希尔排序实际上是一种分组插入排序
* 比较相隔较远距离的数,使得数移动时能跨过多个元素,则进行一次比较就可能消除多个元素交换(距离:称为增量)
* 【增量】一般先取序列的一半,以后每次减半,直到增量为1
*/
public void SortSelf(int[] list) {
Console.WriteLine("希尔排序");
int _length = list.Length;
int _dt = _length / 2;//增量初始值取数组长度的一半
Console.WriteLine("_length={0},_dt={0}", _length, _dt);
while (_dt>=1) //增量大于等于1则进行排序
{
if (_dt%2==0) ++_dt; //保证最后的循环增量为1
Console.WriteLine("最终取得增量_dt="+_dt);
//按增量_dt进行分组,下标为_dt的倍数的放在一组,
//则每次的分组数量为_dt,起始下标分别为0--_dt-1
//每组都要进行一次直接插入排序
for (int i = 0; i < _dt; i++)
{
Console.WriteLine("");
Console.Write("对第{0}组进行排序。",i);
for (int j = i+_dt; j < _length; j+=_dt)
{
Console.Write("j={0},", j);
if (j<_length)
{
if (list[j]<list[j-_dt])//若后面的元素小于前面的值,则将所有比list[j]大的值向后移动
{
var temp = list[j];
int k = 0;
for (k=j-_dt;k>=i&&temp<list[k];k-=_dt)
{
Console.Write("k={0},",k);
list[k + _dt] = list[k];
}
list[k + _dt] = temp;//插入最后比它小的后面
}
}
}
}
Console.WriteLine("");
_dt /= 2;
}
}
public void ShellTest() {
int[] array = new int[] { 1, 5, 3, 6, 10, 55, 9, 2, 87, 12, 34, 75, 33, 47 ,44,99};
for (int i = 0; i < array.Length; i++)
{
Console.Write("{0},", array[i]);
}
SortSelf(array);
for (int i = 0; i < array.Length; i++)
{
Console.Write("{0},", array[i]);
}
Console.ReadKey();
}
}
}
运行效果如下: