希尔排序( Shell Sort)
原文地址:http://www.stoimen.com/blog/,在此感谢作者!
Insertion sort is a great algorithm, because it’s very intuitive and it is easy to implement, but the problem
is that it makes many exchanges for each “light” element in order to put it on the right place. Thus
“light” elements at the end of the list may slow down the performance of insertion sort a lot. That is why
in 1959 Donald Shell proposed an algorithm that tries to overcome this problem by comparing items of
the list that lie far apart.
How to choose gap size
Not a cool thing about Shell sort is that we’ve to choose “the perfect” gap sequence for our list. However
this is not an easy task, because it depends a lot of the input data. The good news is that there are some
gap sequences proved to be working well in the general cases.
Shell Sequence
Donald Shell proposes a sequence that follows the formula FLOOR(N/2 ), then for N = 1000, we get the
following sequence: [500, 250, 125, 62, 31, 15, 7, 3, 1]
Pratt Sequence
Pratt proposes another sequence that’s growing with a slower pace than the Shell’s sequence. He
proposes successive numbers of the form (2^q)* (3^q) or [1, 2, 3, 4, 6, 8, 9, 12, …].
Knuth Sequence
Knuth in other hand proposes his own sequence following the formula (3^k – 1) / 2 or [1, 4, 14, 40, 121, …]
Complexity
Yet again we can’t determine the exact complexity of this algorithm, because it depends on the gap
sequence. However we may say what is the complexity of Shell sort with the sequences of Knuth, Pratt
and Donald Shell. For the Shell’s sequence the complexity is O(n*n ), while for the Pratt’s sequence it is
O(n*log (n)). The best approach is the Knuth sequence where the complexity is O(n^(3/2) ), as you can see
on the diagram bellow.
Application
Well, as insertion sort and bubble sort, Shell sort is not very effective compared to quicksort or merge
sort. The good thing is that it is quite easy to implement (not easier than insertion sort), but in general it
should be avoided for large data sets. Perhaps the main advantage of Shell sort is that the list can be
sorted for a gap greater than 1 and thus making less exchanges than insertion sort.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!