Basic
idea: Divide the sequence to be sorted into several sequences, and perform direct insertion sorting on these sequences.
Specific
operation: select the increment d (less than the sequence Length n), divide the sequence into n/d sequences, perform direct insertion sorting on the divided sequence
and select an increment d1, d1<d, repeat the above steps
until dn = 1 ends
Take d=5 23 52 12 63 8 17 28 72 36 41 ---------------------------------------------- 23 17 |_______________________| 52 28 |_______________________| 12 72 |_______________________| 63 36 |_______________________| 8 41 |_______________________| One-way sorting results: 17 28 12 36 8 23 52 72 63 41 ---------------------------------------------- take d=2 17 12 8 52 63 |_________|________|_________|_________| 28 36 23 72 41 |________|_________|________|_________| Second sorting result: 8 23 12 28 17 36 52 41 63 72 --------------------------------------------- take d=1 Three sorting results: 8 12 17 23 28 36 41 52 63 72
Time complexity:
It is difficult to judge the exact time complexity, which is related to the chosen increment d
Worst case and average case: O(n*log(n))
Stability:
One insertion sort is stable, but Hill sorting is multiple insertions. During different insertion sorting processes, the position of the same element in the respective insertion sorting may change, so it is an unstable sorting
python code example: shell_sort.py
def shell_sort(l): length = len(l) d = length/2 #The initial increment d is selected as half of the sequence while(d >= 1): for i in range(d, length): #Insert l[d...n-1] into each group of ordered subsequences j = i - d while(j >= 0 and l[j] > l[j+d]): #Comparison of two elements of distance increment d tmp = l[j] l[j] = l[j+d] l[j+d] = tmp j -= d #In increments of d, continue to cycle through the elements in the subsequence d = d/2 #Next increment selection if __name__ == '__main__': l = [93,102,36,82,76,84,55,63,49,27] shell_sort(l) print('result:' + str(l)
Lua code example: shell_sort.lua
require "math" function shell_sort(t) length = table.getn(t) d = math:floor(lenght/2) while(d >= 1) do for i = d+1, length do -- insert t[d...n-1] into each group of ordered subsequences j = i - d while(j > 0 and t[j] > t[j+d]) do tmp = t[j] t[j] = t[j+d] t[j+d] = tmp j = j - d end end d = math:floor(d/2) end end t = {93,102,36,82,76,84,55,63,49,27} shell_sort(t) for _, v in ipairs(t) do print v end