In this article, we will study the shell sort and its algorithm with python code along with its output.
According to Wikipedia :- Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange.
Example :
def ShellSort(arr):
n = len(arr)
h = n // 2
while h > 0:
for i in range(h, n):
t = arr[i]
j = i
while j >= h and arr[j - h] > t:
arr[j] = arr[j - h]
j -= h
arr[j] = t
h = h // 2
return arr
arr = [45,22,65,78,9,23,89,52]
print("Before Sorted :: ",arr)
print("After Sorted :: ",ShellSort(arr))
Output :
Before Sorted :: [45, 22, 65, 78, 9, 23, 89, 52]
After Sorted :: [9, 22, 23, 45, 52, 65, 78, 89]
As it has an improved average time complexity, shell sort is very efficient for a smaller and medium-size list. The efficiency of shell sort is better than that of insertion sort and almost five times than that of bubble sort
Ask anything about this examples