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

四、希尔排序

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;
			}
		}
	}
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值