基本排序算法之1——希尔排序shellsort

  希尔排序的时间复杂度在O(N)到O(N2)之间,在大量数据排序中实践性能超过堆排序。特点是算法简单但是分析复杂。下面是实现:

/*
 * a[] is an array to be sorted
 * n1 is the T array length
 * inc[] is the array to indecate the increasement
 * n2 is the inc array length
 */
template<typename T>
void shellsort(T a[],int n1,int inc[],int n2)
{
	for(int i=0;i<n2;++i)
	{
		for(int j=inc[i];j<n1;++j)
		{
			T tmp = a[j];
			int k;
			for(k=j;k>=inc[i];k-=inc[i])
			{
				if(tmp<a[k-inc[i]])
					a[k]=a[k-inc[i]];
				else
					break;
			}
			a[k]=tmp;
		}
	}
}

  需要注意的几点:

    1.希尔排序要参考递减序列,可以采用2k-1(值<N)序列。大数据量的时候采用sedgewick序列。

    2.每一次间隔排序实际上是一个插入排序而不是冒泡。所以要从后向前遍历。

原文地址:https://www.cnblogs.com/jwk000/p/3116714.html