经典排序算法之实现(三)

来源:互联网 发布:js获取ip和端口 编辑:程序博客网 时间:2024/06/05 11:22

四、希尔排序

1、算法描述

     算法先将要排序的一组数按某个增量dn/2,n为要排序数的个数)分成若干组,每组中记录的下标相差d.对每组中全部元素进行直接插入排序,然后再用一个较小的增量(d/2)对它进行分组,在每组中再进行直接插入排序。当增量减到1时,进行直接插入排序后,排序完成。

     2、算法演示

      初始:d=5
   49 38 65 97 76 13 27 49* 55 04

   49 13
   |-------------------|
   38 27
   |-------------------|
   65 49*
   |-------------------|
   97 55
   |-------------------|
   76 04
   |-------------------|
   一趟结果
   13 27 49* 55 04 49 38 65 97 76

   d=3
   13 27 49* 55 04 49 38 65 97 76
   13 55 38 76
   |------------|------------|------------|
   27 04 65
   |------------|------------|
   49* 49 97
   |------------|------------|
   二趟结果
   13 04 49* 38 27 49 55 65 97 76


   d=1
   13 04 49* 38 27 49 55 65 97 76
   |----|----|----|----|----|----|----|----|----|
   三趟结果
   04 13 27 38 49* 49 55 65 76 97


     3、程序代码

#include<iostream>using namespace std;void insertSort(int a[], int len);void shellSort(int a[], int len);int len;int *a;void main(){cout<<"请输入要排序的数列的长度:";cin>>len;cout<<"请输入具体的数字序列:";a = new int[len];for(int i = 0; i < len; i++){cin>>a[i];}shellSort(a,len);for(int j=0; j<len; j++){cout<<a[j]<<"   ";}cout<<endl;delete []a;}void shellSort(int a[], int len){if(1 == len)return;else{int asend = (int)(len/2);while(asend>=1){for(int i=0; i<asend; i++){int common = len/asend;int over = len%asend;if(i<over){int *temp = new int[common+1];for(int j=0; j<common+1; j++){temp[j] = a[asend*j+i];}insertSort(temp,common+1);for(int j=0; j<common+1; j++){a[asend*j+i] = temp[j];}delete []temp;}else{int *temp = new int[common];for(int j=0; j<common; j++){temp[j] = a[asend*j+i];}insertSort(temp,common);for(int j=0; j<common; j++){a[asend*j+i] = temp[j];}delete []temp;}}asend = asend/2;}}}void insertSort(int a[], int len){for(int i = 1; i < len; i++){for(int j=i; j>0; j--){if(a[j]<a[j-1]){int t = a[j];a[j] = a[j-1];a[j-1]=t;}}}};


原创粉丝点击