Shell Sort Python (original) (raw)

Last Updated : 6 Nov, 2025

Shell Sort is an improvement over Insertion Sort. Instead of comparing adjacent elements, it compares elements that are far apart using a gap. The gap keeps reducing until it becomes 1, at which point the list is fully sorted. This allows elements to move faster toward their correct positions.

Algorithm Steps

  1. Initialize the gap as half the length of the array (n/2).
  2. Divide the array into smaller sublists, each separated by the gap.
  3. Perform insertion sort within these sublists.
  4. Reduce the gap size and repeat sorting until the gap becomes 0.
  5. Stop when the array is completely sorted.

Working Example

Let’s take a small list for example: [9, 1, 5, 3]. Below is the step-by-step process:

**Initial list: [9, 1, 5, 3], Number of elements = 4 → start with gap = 2.

**Pass 1 (gap = 2):

**Reduce gap: gap = 1 (regular insertion sort step)

**Pass 2 (gap = 1):

Python Implementation

Using Ciura Sequence

This method uses a predefined sequence of gaps based on experimental results (701, 301, 132, 57, 23, 10, 4, 1). The array is first sorted using large gaps and then progressively smaller gaps, ensuring that elements move closer to their correct positions faster.

Python `

def shell_ciura(a): n = len(a) gaps = [701, 301, 132, 57, 23, 10, 4, 1] for g in gaps: if g >= n: continue for i in range(g, n): t = a[i] j = i while j >= g and a[j-g] > t: a[j] = a[j-g] j -= g a[j] = t

arr = [12, 34, 54, 2, 3] shell_ciura(arr) print(arr)

`

**Explanation:

Using Knuth Sequence

This method generates gaps dynamically using the formula gap = 3*gap + 1, starting from 1 and going up until it’s less than the array size. Sorting is then performed for each gap in decreasing order, gradually refining the order until the list becomes fully sorted.

Python `

def shell_knuth(a): n = len(a) g = 1 while g < n//3: g = 3*g + 1 while g > 0: for i in range(g, n): t = a[i] j = i while j >= g and a[j-g] > t: a[j] = a[j-g] j -= g a[j] = t g //= 3

arr = [12, 34, 54, 2, 3] shell_knuth(arr) print(arr)

`

**Explanation:

Using Half-gap Division

This traditional method starts with a gap equal to half of the array length and keeps halving the gap until it becomes 1. At each stage, elements that are gap positions apart are compared and rearranged, resulting in a gradually sorted list.

Python `

def shell_half(a): n = len(a) g = n // 2 while g > 0: for i in range(g, n): t = a[i] j = i while j >= g and a[j-g] > t: a[j] = a[j-g] j -= g a[j] = t g //= 2

arr = [12, 34, 54, 2, 3] shell_half(arr) print(arr)

`

**Explanation:

Please refer complete article on ShellSort for more details!