4、希尔(shell)排序

4、希尔(shell)排序

希尔排序(shell)也即是插入排序的另一种形式,只是简化了每次进行插入排序的时候,数组中的数移动的次数。

#include <bits/stdc++.h>
using namespace std;
void shell_sort(int* a, int len);
void print(int* a, int len, bool isBefore= true);
int main(){
	int arr[10] = {1, 2, 66, 33, 88, 100, 18, 78, 12, 321};
	print(arr, 10);
	cout << "shell排序:" << endl;
	shell_sort(arr, 10);
	print(arr, 10, false); 
	return 0;
}
void shell_sort(int* a, int len){
	int step = len/2;
	int temp;
	int j; 
	while(step){		
	for(int i = step; i < len;i++){//每个组都要做插入排序 
	 //临时存储待插数据
	 temp = a[i];
	 j = i - step;
	 while(j >= 0 && a[j] > temp) {//j的范围,只有a[j]大于temp才往后覆盖
	 a[j + step] = a[j];
	 j-=step; 	
	 }
	 a[j+step] = temp;//temp覆盖回来 
	
	
	} 
	 print(a,10);
		step /= 2;	
	}
}
void print(int* a, int len, bool isBefore){
 	if(isBefore)
 		cout << "before sort:";
 	else
 		cout << "after sort:";
 		
 	for(int i = 0; i< len; i++){
 		cout << a[i] << " ";
	 }
 	cout << endl;
 }

下面来进行分析:

给定一个数组:1, 2, 66, 33, 88, 100, 18, 78, 12, 321

第一次的步长step = 10/2 = 5;

这个时候分成了以下五个小组,对以下五个小组分别进行插入排序,得到

【0】1 【5】100

【2】2 【6】18

【3】66 【8】78

【4】33 【9】12

【5】88 【10】321

得到序列:1 2 66 33 88 100 18 78 12 321,

接着步长step = step/2;也就是 5/2向下取整 step =2,分成以下两个小组:
【0】1 【2】66 【4】88 【6】18 【8】12

【1】2 【3】33 【5】100 【7】78 【9】321

分别对每个小组进行插入排序得到:1 2 12 33 18 78 66 100 88 321

接着step = 1;再次进行插入排序得到:1 2 12 18 33 66 78 88 100 321

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

允谦呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值