一、希尔排序思路
希尔排序是一种分组插入方法。假设待排序的表为R[0 ...n-1],它先取一个小于n的数d1作为它的第一个增量,把表的元素分为d1组,所有相互之间相邻距离为d1的元素归为一组。在同一组内进行直接插入排序。然后取d2作为第二个增量,依次循环,直到增量为1,排序结束。
二、希尔算法
/***********************************************************************
* FUNCTION: 希尔排序算法
* AUTHOR: zhuzi
* DATE: 2018-5-03
* VERSION: v1.0
* NOTES:
* MODIFICATION:
**********************************************************************/
#include <iostream>
using namespace std;
typedef int KeyType;
typedef int InfoType;
typedef struct
{
KeyType key;
InfoType data;
}RecType;
/*********************************************************************
* function: 希尔排序
* parameters: RecType R[], 待排序数组
int n, 数组个数
* return value: 无
**********************************************************************/
void ShellSort(RecType R[], int n)
{
int i, j, gap;
RecType tmp;
gap = n/2;//gap元素间增量
while(gap > 0)//gap=1时,完成排序
{
for(i = gap; i < n; i++)//小组内进行直接插入排序,将R[i]插入有序区合适位置。
{
tmp = R[i];
j = i - gap;
while(j >= 0 && tmp.key < R[j].key)
{
R[j+gap] = R[j];
j = j-gap;
}
R[j + gap] = tmp;
}
gap = gap/2;//gap减半
}
}
/*********************************************************************
* function: 输出元素
* parameters: RecType R[], 有序区数组
int n, 数组元素个数
* return value: 无
**********************************************************************/
void print(RecType R[], int n)
{
for(int i = 0; i < n ; i++)
{
cout << "R[" << i << "] <" << R[i].key << "," << R[i].data << ">" << endl;
}
}
int main(int argc, char* argv[])
{
RecType RT[] = {{1,11},{3,33},{2,22},{5,55},{7,77},{8,88}};
ShellSort(RT, sizeof(RT)/sizeof(RT[0]));
print(RT, sizeof(RT)/sizeof(RT[0]) );
return 0;
}
平均时间复杂度为O(n^1.3)。不稳定排序算法。