希尔排序(Shell Sort)是对直接插入排序的一种改版,其代码也是在插入排序的基础上稍稍经过变化而来。通过一个短小的循环计算最初的位移。从而,通过此增量实现此算法效率高于直接插入排序。
代码实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 希尔排序
{
public class Shellsorter
{
public void sort(int[] list)
{
int i, j,t,h;
for (h = list.Length / 2; h > 0; h = h / 2) // 通过此循环确定增量
{
for (i = h; i < list.Length; i++) //从增量处开始,依次往后,进行插入排序
{
t = list[i];
for (j = i; j >= h; j = j - h) //此处即通过简单插入排序代码变化过来
{
if (list[j - h] > t)
list[j] = list[j - h];
else
break;}
list[j] = t;
}
}
}
}
class Program
{
static void Main(string[] args)
{
int[] iArry = new int[] { 1, 13, 3, 6, 10, 55, 98, 2, 87, 12, 34, 75, 33, 47 };
Shellsorter ii = new Shellsorter();
ii.sort(iArry);
for (int i = 0; i < iArry.Length; i++)
{
Console.Write("{0} ", iArry[i]);
}
}
}
}
时间复杂度最坏情况为O(n²),最好情况为O( n^1.3);空间复杂度为O(1),因为其只借助了一个空间变量。