#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Sorting Algorithms

Shell Sort in Data Structure — Algorithm, Visualization and Complexity

Shell Sort is an optimization of Insertion Sort that allows the exchange of elements that are far apart. It works by first sorting elements that are a certain 'gap' distance apart, then progressively reducing the gap until it becomes 1 (a final regular insertion sort pass).

How It Works (Visualization)

For an array of size 8 with an initial gap of 4, elements at positions (0,4), (1,5), (2,6), (3,7) are compared and sorted first. The gap is then reduced (commonly halved, e.g., to 2), and the process repeats with smaller sub-groups, until the gap becomes 1, performing a final full insertion sort pass on the now mostly-sorted array.

def shell_sort(arr):
    n = len(arr)
    gap = 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 //= 2
    return arr

Complexity

Gap SequenceWorst Case Time
n/2, n/4, ..., 1 (Shell's original)O(n²)
Knuth's sequence (3k+1)O(n^1.5)
Hibbard's sequenceO(n^1.5)

Advantages

  • Significantly faster than plain Insertion Sort or Bubble Sort for medium-sized arrays.
  • In-place — requires only O(1) extra space.
  • Simple to implement compared to Merge Sort or Quick Sort.

Applications

  • Sorting medium-sized datasets where simplicity and low memory use matter.
  • Embedded systems with limited memory.
  • Used historically in the uClibc library's qsort implementation for small arrays.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course