// ShellSort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
// SelectSort.cpp : Defines the entry point for the console application.
#include "iostream"
using namespace std;
// 说明:排序算法 - 希尔排序, 希尔排序是直接插入排序的改进版本, 它使得传统算法突破了O(n2)级别;
// 思路:希尔排序将相隔某个“增量”的记录组成一个子序列,实现跳跃式的移动,每次子序列的排序与直接插入排序类似。
void ShellSort(double a[], int n)
{
int iInc = n;
while (iInc > 1)
{
iInc = iInc / 3 + 1;
for (int i=1; i<n; i+=iInc)
{
double dTemp = a[i];
int j=i;
for (NULL; j>=iInc && dTemp < a[j-iInc]; j-=iInc)
{
a[j] = a[j-iInc];
}
if (j != i)
{
a[j] = dTemp;
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
double a[] = {2.0, 5.4, 4.0, 8.0, 3.0, 5.0, 1.0, 9.0, 7.0};
int n = sizeof(a) / sizeof(*a);
cout<<"排序前:\n";
for each (double x in a)
{
cout<<x<<" ";
}
cout<<endl;
ShellSort(a, n);
cout<<"排序后:\n";
for each (double x in a)
{
cout<<x<<" ";
}
cout<<endl;
return 0;
}
算法还有改进之处,比如在里层for循环之前加if判断;