Easy Tutorial
❮ Python Att Dictionary Pop Ref Math Exp ❯

Python Shell Sort

Python3 Examples

Shell Sort, also known as the Diminishing Increment Sort, is a more efficient variation of the Insertion Sort. However, Shell Sort is not a stable sorting algorithm.

The basic idea of Shell Sort is to divide the entire sequence of records to be sorted into several sub-sequences and perform direct insertion sort on them separately. When the records in the entire sequence are "almost sorted," a direct insertion sort is performed on all records.

Example

def shellSort(arr): 

    n = len(arr)
    gap = int(n/2)

    while gap > 0: 

        for i in range(gap,n): 

            temp = arr[i] 
            j = i 
            while  j >= gap and arr[j-gap] > temp: 
                arr[j] = arr[j-gap] 
                j -= gap 
            arr[j] = temp 
        gap = int(gap/2)

arr = [ 12, 34, 54, 2, 3] 

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

shellSort(arr) 

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

Executing the above code produces the following output:

Before sorting:
12
34
54
2
3

After sorting:
2
3
12
34
54

Python3 Examples

❮ Python Att Dictionary Pop Ref Math Exp ❯