算法:希尔排序(Shell Sort)

本文介绍了一种改进的插入排序——希尔排序。希尔排序通过先对较远距离的元素进行排序,再逐渐减小这个距离,最终达到完全排序的目的。文章详细解释了希尔排序的实现过程,并提供了具体的代码示例。

背景

在三种简单的排序算法中(冒泡、选择和插入)插入排序的算法最好,不过插入过程可能需要进行大量的移动,如何尽可能少的移动元素呢?希尔排序正是基于对这个问题的思考而想出来的,考虑到希尔排序对已排序数组的排序效率尤为好(接近O(n)),因此希尔排序会先按照较大的间隔,对间隔的元素进行插入排序,然后将间隔缩小重复上述过程,直到间隔为 1。

实现

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace DataStuctureStudy.Sorts
 8 {
 9     class ShellSort
10     {
11         public static void Sort(int[] items)
12         {
13             var h = 1;
14             while (h <= (items.Length - 1) / 3)
15             {
16                 h = 3 * h + 1;
17             }
18 
19             // 对间隔为 h 的元素进行排序,如:(0,h,2h)、(1,h + 1,2h + 1)。
20             while (h >= 1)
21             {
22                 // 将 outer 对应的元素按照插入排序的算法(间隔为 h)插入到指定的位置。
23                 // h 之前的元素都是已排序的。
24                 for (var outer = h; outer < items.Length; outer++)
25                 {
26                     var temp = items[outer];
27                     var inner = outer;
28                     while (inner >= h && items[inner - h] > temp) // 闲了得思考一下:不变量和 while。
29                     {
30                         items[inner] = items[inner - h];
31                         inner = inner - h;
32                     }
33                     items[inner] = temp;
34                 }
35                 h = (h - 1) / 3;
36             }
37         }
38     }
39 }

备注

间隔的选择是一个关键因素,这里我选择了一个大家经常使用的算法。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值