希尔排序的实质就是分组插入排序,该方法又称缩小增量排序,因DL.Shell于1959年提出而得名。
C++代码:
#include <iostream>
using namespace std;
/*
* 打印数组
*/
void printArray(int array[],int length)
{
for (int i = 0; i < length; ++i)
{
cout << array[i] << " ";
}
cout << endl;
}
/*
* 插入排序
* 相隔gap个数进行比较,插入排序
*/
void shell_insertion(int *array,int length,int gap)
{
for (int i = gap; i < length; i++)//从数组第gap个元素开始
{
int key = array[i];
int j = i - gap;
while(j >= 0 && array[j] > key)
{
array[j + gap] = array[j];
j = j - gap;
}
array[j + gap] = key;
}
}
/*
* 希尔排序
*/
void shellSort(int *array,int length,int data) //data < length
{
int count = data;
int temp = length / count;
int arge = 0;
while(temp >= 1)
{
cout << temp << " ";
arge = temp;
shell_insertion(array,length,temp);
temp = temp / count;
if (temp == 0 && temp != 1)
{
shell_insertion(array,length,1);
}
}
cout <<endl;
}
int main()
{
int array[9] = {9,2,5,1,8,6,3,4,7};
int length = sizeof(array) / sizeof(int) ;
int data = 3;
shell_insertion(array,length,data);
shellSort(array,length,data);
printArray(array,length);
return 0;
}
//结果:
//3 1
//0 1 2 3 4 5 6 7 8 9