数据结构与算法——希尔排序(shell排序)

//希尔排序(shell排序)
#include<iostream>
using namespace std;
void print(int a[], int n ,int i)
{
cout<<i <<":";
for(int j= 0; j<n; j++)
{
cout<<a[j] <<" ";
}
cout<<endl;
}
/* 直接插入排序的一般形式 *
* d 缩小增量,如果是直接插入排序,d=1 */
void ShellInsertSort(int a[], int n, int d)
{
for(int i= d; i<n; ++i)
{
if(a[i] < a[i-d])//若i所处位置的数大于i-d位置的数,则直接插入,否则元素移动,腾出空间后插入
{
int j = i-d;
int x = a[i]; //复制为哨兵,即存储待排序元素
while(x < a[j]) //查找在有序表的插入位置
{
a[j+d] = a[j];
j -= d; //元素后移
}
a[j+d] = x; //插入到正确位置
}
print(a, n,i );
}
}
/** 先按增量d(n/2,n为要排序数的个数)进行希尔排序**/
void shellSort(int a[], int n)
{
int d = n/2;
while( d >= 1 )
{
ShellInsertSort(a, n, d);
d = d/2;
}
}
int main( )
{
int a[9] = {1,1,5,7,2,4,9,6,8};
int length=sizeof(a)/sizeof(a[0]);
shellSort(a,length); //希尔插入排序
print(a,length,length);
}

 

posted @ 2015-10-12 16:26  驻足一分钟  阅读(158)  评论(0编辑  收藏  举报