希尔排序算法
很多情况下需要用到一些基础的排序算法,接下来分析希尔排序算法:
1.把数组R[n]元素分为d=n/2组,d由元素距离为d的放在一个组;
2.对每组组内元素进行直接插入排序
3.d=d/2,d>0时,继续执行第一二步
一、构图分析:
二、 代码实现:
#include<iostream>
#include<iomanip>
using namespace std;
typedef char KeyType;//自定义需要排序数组类型
void shellQueue(KeyType R[],int n)
{
int i;
int j;
KeyType temp;
int gap;
gap = n/2;//初始化增量的值
while(gap > 0)
{
for( i = gap; i < n; i++ )//对所有间隔gap的元素进行直接插入排序
{
temp = R[i];
j = i - gap;
while(j > 0 && temp < R[j])//对相隔gap位置的元素进行排序
{
R[j+gap] = R[j];
j = j - gap;
}
R[j+gap] = temp;
}
gap = gap/2;//减小增量
}
cout<<"用希尔排序算法得到的序列:"<<endl;
for( i = 0; i < n; i++)
{
cout<<R[i];//格式化输出
}
}
int main()
{
char a[4]={'a','b','c','d'};
shellQueue(a,4);
return 0;
}
三、算法分析:
比直接插入排序快很多,具体为:
时间复杂度:o(n^1.3)
空间复杂度:o(1)