本文原创,转载请注明出处(羅小亮博客)。如果本文如果有雷同观点,纯属巧合。如果有引述他人成果,必会给出处。
希尔排序其实只是在直接插入排序上进行改进,直接插入排序是按照间隔1来进行排序的,而希尔排序这里是按照间隔gap来进行排序的。读者可以参照我的上一篇文章“用C++实现直接插入排序”,理解了直接插入排序后,只需要把直接插入排序中的间隔1修改成自己gap就行
#include <iostream>
using namespace std;
void ShellSort(int a[],int n);
int main()
{
int a[10]={5,8,2,1,6,7,9,4,3,0};
ShellSort(a,10);
for(int i=0;i<10;++i)
cout << a[i];
cout << endl;
system("pause");
return 0;
}
void ShellSort(int a[],int n)
{
int temp,i,j;
int gap=n;
do
{
gap=gap/3+1;
for(i=gap;i<n;++i)
{
if(a[i]<a[i-gap])
{
temp=a[i];
for(j=i-gap;(j>=0)&&(a[j]>temp);j=j-gap)
{
a[j+gap]=a[j];
}
a[j+gap]=temp;
}
}
}while(gap>1);
}