希尔排序:也是一种“插入排序,在插入排序的基础上得来的,引入了“gap”,有间隔的排序,先使其基本有序,画图更清楚。
#include<iostream>
using namespace std;
void insertsort(int *p, int length,int gap)
{
int i=0, j=0;
for (i = gap; i <=(length-gap); i++)
{
int temp = p[i];
for (j = i - gap; j >= 0 && p[j]>temp; j-=gap) //有间隔的插入排序
{
p[j + gap] = p[j];
}
p[j + gap] = temp;
}
}
void shellsort(int *p, int length)
{
for (int gap = 3; gap > 0; gap--)
{
insertsort(p, length, gap);
}
}
int main()
{
int p[] = { 2, 3, 7, 4, 5, 9 ,10,6,8};
int length = 9;
shellsort(p,length);
for (int i = 0; i < length; i++)
{
cout << p[i] << " ";
}
}