Open In App

Shell Sort – Python

Last Updated : 03 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Shell Sort is an advanced version of the insertion sort algorithm that improves its efficiency by comparing and sorting elements that are far apart. The idea behind Shell Sort is to break the original list into smaller sublists, sort these sublists, and gradually reduce the gap between the sublist elements until the list is sorted.

Shell Sort Algorithm

Step 1 − Start
Step 2 − Initialize the value of gap size, say h.
Step 3 − Divide the list into smaller sub-part. Each must have equal intervals to h.
Step 4 − Sort these sub-lists using insertion sort.
Step 5 – Repeat this step 2 until the list is sorted.
Step 6 – Print a sorted list.
Step 7 – Stop.

Below is the implementation of Shell Sort:

Python
def shellSort(arr):

    # Start with a big gap, then reduce the gap
    n = len(arr)
    gap = n/2

    # Do a gapped insertion sort for this gap size.
    # The first gap elements a[0..gap-1] are already in gapped
    # order keep adding one more element until the entire array
    # is gap sorted
    while gap > 0:

        for i in range(gap,n):

            # add a[i] to the elements that have been gap sorted
            # save a[i] in temp and make a hole at position i
            temp = arr[i]

            # shift earlier gap-sorted elements up until the correct
            # location for a[i] is found
            j = i
            while j >= gap and arr[j-gap] >temp:
                arr[j] = arr[j-gap]
                j -= gap

            # put temp (the original a[i]) in its correct location
            arr[j] = temp
        gap /= 2


# Driver code to test above
arr = [ 12, 34, 54, 2, 3]

n = len(arr)
print ("Array before sorting:")
for i in range(n):
    print(arr[i]),

shellSort(arr)

print ("\nArray after sorting:")
for i in range(n):
    print(arr[i]),

Output
Array before sorting:
12 34 54 2 3 
Array after sorting:
2 3 12 34 54

Time Complexity: O(n2)

Auxiliary Space: O(1)

Please refer complete article on ShellSort for more details!


Next Article

Similar Reads