ReviewForJob——希尔排序(缩小增量排序)之塞奇威克增量序列

【0】README

0)希尔排序是基于插入排序的。将插入排序算法 内for循环中的所有 1 改为增量就可以。。bingo。。 插入排序源码

1)本文旨在给出 希尔排序(缩小增量排序)之塞奇威克增量序列 的源码实现;

2)为什么要求 塞奇威克增量序列?  

reason1)要知道, 塞奇威克 提出了几种增量序列,最坏运行时间为 O(N^4/3),平均运行时间为 O(N^7/6); 其提出的增量序列中的最好序列是 {1, 5, 19, 41, 109, ......},该序列中的项或者是 9*4^i - 9*2^i + 1 或者是 4^i  - 3*2^i + 1;

reason2)基于塞奇威克增量序列的希尔排序(缩小增量排序) 要 快于 花费 O(NlogN) 的 堆排序;

3)本文末会给出 基于 塞奇威克增量序列 的 希尔排序源码实现,希尔排序的基础知识参见 

http://blog.csdn.net/pacosonswjtu/article/details/49660799


【1】下面给出求塞奇威克增量序列 的 分析和源码实现

1)分析


2)源码如下

#include <stdio.h>
#include <math.h>
// 对增量序列赋值 和 找出所需要的最大轮数.
// 如 Rebort Sedgewick(罗伯特·塞奇威克) 提出的 increment = 9*4^i - 9*2^i +1  或 increment = 4^i - 3*2^i +1;
// incrementSeq[] 起点从 0 开始.
int incrementSeqFunc(int* incrementSeq, int length)
{	
	int i, startup1 =0 , startup2 = 2;

	for(i=0; i<length; i++)
	{
		if(i%2==0)
		{
			incrementSeq[i] = 9*pow(4, startup1) - 9*pow(2, startup1) +1;
			startup1++;
		}
		else
		{
			incrementSeq[i] = pow(4, startup2) - 3*pow(2, startup2) +1;
			startup2++;
		}
		if(incrementSeq[i] >= length)
		{
			break;
		}
	}
	return i; // 排序轮数,每轮都使用(比上一轮)缩小的增量序列
}

void printArray(int data[], int size)
{
	int i;
 
	for(i = 0; i < size; i++)
		printf("%d ", data[i]);
	
	printf("\n");
}
#include "p167_shell_sort.h"

int main()
{	
	int incrementSeq[255];	
	int length = 600;
	int round;

	round = incrementSeqFunc(incrementSeq, length);
	printArray(incrementSeq, round);	
}

3)打印结果



【2】基于塞奇威克增量序列 的 希尔排序源码

Attention)you can also checkout the source code from https://github.com/pacosonTang/dataStructure-algorithmAnalysis/tree/master/chapter7/review/p167_shell_sort 

void shell_sort(int* array, int length)
{	
	int incrementSeq[255]; // 增量序列(startup == 0).
	int i, j, round=incrementSeqFunc(incrementSeq, length);
	int increment, temp;

	for(; round>=1; round--)
	{
		increment = incrementSeq[round-1];
		for(i=1*increment; i<length; i+=increment) // 默认地,array[0*increment]有序,所以从1*increment开始.
		{
			temp = array[i]; // 第1个无序成员.
			for(j=i-increment; j>=0; j-=increment) // j 在有序部分进行滑动.
			{
				if(temp < array[j])
				{
					array[j+increment] = array[j];
				}
				else
				{
					break;
				}
			}
			array[j+increment] = temp;
		}
	}	
}
#include "p167_shell_sort.h"

int main()
{		
	int array[] = {100, 1000, 100, 10, 6, 2, 19, 25, 15, 55, 
				   35, 5, 110, 120, 119};
	int length = 15;	
	
	shell_sort(array, length);
	printArray(array, length);
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值