希尔排序算法的命名来自它的发明者,唐纳德.希尔。
从本质上来说,希尔排序是更进一步的插入排序,附带插入排序的内容:插入排序-C#描述
希尔排序算法采用增量对远距离元素进行排序,这个增量一般选用数组长度/2为开始,依次按照等比数列排序,公比为1/2直到这个增量变为小于1,彼此对应的两个元素相互比较,按照从小到大的顺序依次排列,如图
由此可以知道希尔排序也是两层循环,外部循环遍历整个数组,内部循环依次比较大小。
算法设计:
- 选择一个增量,一般来说,增量是数组长度的1/2;
- 遍历整个数组,确保每一个元素都能够排序;
- 增量匹配元素;
- 比较大小,交换位置;
- 增量压缩1/2,重复步骤2,3;
- 当增量小于1时,排序完成;
public static void ShellSort(int[] arr)
{
int n = arr.Length / 2;//选择增量步骤1
while (n >= 1)//步骤6
{
for (int i = 0; i < arr.Length; i++)//遍历整个数组,步骤2
{
for (int j = i + n; j < arr.Length; j += n)
//增量匹配的元素,步骤3
{
//增量匹配的元素比较大小,步骤4
int temp = arr[j];
int loc = j - n;
while (arr[loc] > temp && loc >= i)
{
arr[j] = arr[loc];
arr[loc] = temp;
j++;
}
}
}
n = n / 2;//步骤5
}
}
完整代码
using System;
namespace hillsortalgorithm
{
class Program
{
static void Main(string[] args)
{
int[] nums = new int[] { 16, 174, 19, 55, 53, 463, 22, 33, 332, 133 };
ShellSort(nums);
Showarr(nums);
Console.ReadKey();
}
public static void ShellSort(int[] arr)
{
int n = arr.Length / 2;
while (n >= 1)
{
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + n; j < arr.Length; j += n)
{
int temp = arr[j];
int loc = j - n;
while (arr[loc] > temp && loc >= i)
{
arr[j] = arr[loc];
arr[loc] = temp;
j++;
}
}
}
n = n / 2;
}
}
public static void Showarr(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
}
}
排序结果