数据结构与算法——希尔排序(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);
}

 

转载于:https://www.cnblogs.com/yangyan1006/p/4872029.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值