希尔排序可以说是基于插入排序的一种更高级的排序算法。它是原址排序,但不稳定,时间复杂度
- 它与插入排序的不同之处在于,它将待排的序列以间隔为 取出,这样把整个待排序序列分成若干个子集,然后对子集序列用插入排序法进行排序;
- 再令 ,再次进行与第一步类似的步骤;
- 直到 , 完成最后一次排序后,待排序序列就完成排序了。
PS 注意: Shell排序有一个关键步骤是序列选取间隔 的选择,首先可令它为待排序列长度的一半
下面以VS2010运行环境给出了实现代码,且当待排序的序列的个数N=20(较小)时,运行结果如下:
当N=10000时,排序时间为如下:
The sorted-time spending is 3 ms
下面给出Shell排序的代码片段
void Shell_Sort(int *arr)
{ //Codes of the Shell_Sort Algorithm
if(NULL==arr)
throw exception("Invalid parameters.");
int ii,increment,flag,temp;
for(increment=N/2;increment>0;increment/=2)
for(ii=increment;ii<N;++ii){
temp=arr[ii];
flag=ii-increment;
while(flag>=0 && arr[flag]>temp){
arr[flag+increment]=arr[flag];
flag-=increment;
}
flag+=increment;
arr[flag]=temp;
}
}
//主函数与其他子函数
#include "stdafx.h"
#include <iostream>
#include <exception>
#include <ctime>
using namespace std;
const int N=20;//待排序序列的个数
const int Range=3000;//待排序序列的大小范围
void Swap(int &,int &);
void InputNumber(int *,int );
void OutputNumber(int *,int);
void Shell_Sort(int *);
int _tmain(int argc, _TCHAR* argv[])
{
int arr[N]={0};
InputNumber(arr,N);
cout<<"The InputNumbers are--------------"<<endl;
OutputNumber(arr,N);
auto tstart=clock();
Shell_Sort(arr);
auto tend=clock();
auto TotalTime=tend-tstart;
cout<<"The sorted-time spending is "<<TotalTime<<" ms"<<endl;
cout<<endl<<"The Sorted Numbers are--------------"<<endl;
OutputNumber(arr,N);
return 0;
}
void InputNumber(int *arr,int N)
{
if(arr==NULL)
return;
for(int ii=0;ii<N;++ii)
arr[ii]=rand()%Range;
}
void OutputNumber(int *arr,int N)
{
for(int ii=0;ii<N;++ii)
cout<<arr[ii]<<'\t';
cout<<endl;
}
inline void Swap(int &lhs,int &rhs)
{
int temp;
temp=lhs;
lhs=rhs;
rhs=temp;
}
下面一篇将介绍快速排序,也同样的给出了实现代码和排序运行时间