希尔排序(c++实现)

来源:互联网 发布:linux cpu 多核 切换 编辑:程序博客网 时间:2024/05/22 08:17

  希尔(Shell)排序的基本思想是:先取一个小于n的整数d1作为第一个增量把文件的全部记录分成d1个组。所有距离为d1的倍数的记录放在同一个组中。先在各组内进行直接插入排序;然后,取得第二个增量d2<d1重复上述的分组和排序,直至所取的增量di=1,即所有记录放在同一组中进行直接插入排序为止。该方法实质上是一种分组插入方法。


一般取d1=n/2,di+1=di/2。如果结果为偶数,则加1,保证di为奇数。





代码:

// 希尔排序.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include<iostream>#include<string>using namespace std;void shellSort(int a[],int length);int main(){int array[]={3,7,1,5,4};int length=sizeof(array)/sizeof(int);cout<<"before sort"<<endl;for(int i=0;i<length-1;i++){cout<<array[i]<<' ';}cout<<array[length-1]<<endl;shellSort(array,sizeof(array)/sizeof(int));cout<<"after sort"<<endl;for(int i=0;i<length-1;i++){cout<<array[i]<<' ';}cout<<array[length-1]<<endl;return 0;}void shellSort(int a[],int length){int step;step=length/2;if(step%2==0){step++;}while(step>0){for(int j=step;j<length;j++){int temp=a[j];int i=j-step;while(i>=0&&a[i]>temp){a[i+step]=a[i];i=i-step;}if(i!=j-step)a[i+step]=temp;}if(step==1)break;step=step/2;if(step%2==0)step++;}}
结果: