希尔排序(Shellsort)的名字源于其发明者Donald Shell, 被认为是冲破2次时间界限的第一批算法,但最坏情况时间复杂度为O(n2)。它通过比较相距一定间隔的元素来进行工作;各躺比较的距离逐渐减小,直到相邻元素比较(此时变成了插入排序)。
希尔排序使用增量序列h1、h2、h3…h(t)。只要h1 = 1任何增量序列是可行的,不过有些增量序列比另外一些更好。在使用增量hk的一趟排序后,对于每一个i我们有A[i] <= A[i + h(k)],所以相隔hk的元素都被排序。此时称序列是hk-排序的。
增量序列一种流行(但不好)的做法是使用shell推荐的序列:h(t) = [N / 2] 和 h(k) = [h(k + 1) / 2]
算法实现如下,对比插入排序算法可以更好认识希尔排序。
void shell_sort(int array[], int n)
{
int increase, i, j, tmp;
/*使用shell推荐的增量序列*/
for (increase = n / 2; increase > 0;
increase /= 2) {
/*i = 1时就变成了插入排序*/
for (i = increase; i < n; i++) {
tmp = array[i];
for (j = i; j > 0 && array[j - increase] >= tmp; j -= increase)
array[j] = array[j - increase];
array[j] = tmp;
}
}
}
int main()
{
int array[] = {5, 4, 3, 2, 1};
int n = sizeof(array) / sizeof(int);
shell_sort(array, n);
return 0;
}
Hibbard增量序列1、3、5、7,……,奇数序列,能使希尔排序获得更好的时间效率,使用Hibbard增量的希尔排序的最坏情形运行时间为O(n3/2)。