希尔排序
希尔排序又叫缩小增量排序,也是一直插入排序算法,是直接插入排序的一种改进。
算法思路:先取一个小于n的整数dk作为第一个增量,将array分成dk组,将所有相距dk的倍数的元素分到同一个组中,先在各自组内进行直接插入排序,然后逐步减小增量dk的大小,直到dk的值为1,这时就是一个对所有元素的直接插入排序,排序结束。
希尔排序的C++实现:
/****************************
*Name:希尔排序.cpp
*Tags:排序
*Note:
*****************************/
#include <iostream>
#define MAX_SIZE 1000
using namespace std;
int ShellSort(int *, int, int);
int main()
{
int i, array[MAX_SIZE];
int len;
cout << "Input the size of the array :";
cin >> len;
for(i = 0; i < len; i++) {
cin >> array[i];
}
ShellSort(array, 0, len); //ShellSort
cout << "After ShellSort: " << endl;
for(i = 0; i < len; i++) {
cout << array[i] << " ";
}
cout << endl;
return 0;
}
int ShellSort(int *array, int start, int end)
{
int i, j, dk;
int temp;
dk = (end-start)/2; //取总数的一半为开始增量
while(dk > 0) {
for(i = start+dk; i < end; i++) {
temp = array[i];
j = i-dk;
while(j >= 0 && array[j] > temp) {
array[j+dk] = array[j];
j -= dk;
}
array[j+dk] = temp;
}
dk /= 2; //增量每次折半
} //排序过程
return 0;
}
希尔排序的时间复杂度为O(Nlog(N)2), 由于一次插入排序是稳定的,不会改变相同元素的相对顺序,但在不同的插入排序过程中,相同的元素可能在各自的插入排序中移动,最后其稳定性就会被打乱,所以shell排序是不稳定的。
当N值很大时数据项每一趟排序需要的个数很少,但数据项的距离很长。当N值减小时每一趟需要和动的数据增多,此时已经接近于它们排序后的最终位置。 正是这两种情况的结合才使希尔排序效率比插入排序高很多。
对于所有的排序需求,都可以用希尔排序来处理,当效率不是很理想的情况下,可以考虑用快排等算法来处理。