VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shell-sort/

⇱ Shell Sort - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shell Sort

Last Updated : 20 Dec, 2025

Shell Sort, also known as Shell's method, is an in-place comparison sort and an optimization of Insertion Sort. It improves upon the efficiency of Insertion Sort by allowing elements to be moved over larger distances in the initial stages, which significantly reduces the number of swaps required, especially for larger datasets. 

  • It was considered as the first algorithm to break the O(n²) time complexity barrier for sorting.
  • It works by comparing elements that are far apart first, then gradually reducing the gap. This allows faster movement of elements across the array.

Steps used in the algorithm are,

  1. Choose a gap sequence (commonly n/2, n/4, ... , 1).
  2. Sort elements at each gap using Insertion Sort.
  3. Reduce the gap and repeat until the gap becomes 1.

Let's sort the list [22, 34, 25, 12, 64, 11, 90, 88, 45] using Shell Sort :



Output
2 3 12 34 54 

Complexity Analysis of Shell Sort:

Time Complexity:

  • Best Case: O(n log n), when the array is already nearly sorted (depends on gap sequence).
  • Average Case: Between O(n^1.25) and O(n^1.5), depending on the chosen gap sequence.
  • Worst Case: O(n²), with simple gap sequences like n/2, n/4, …, 1.

Auxiliary Space: O(1), as it sorts in-place.
Stability: Not stable (equal elements may not retain their original relative order).

Applications of Shell Sort:

  • Suitable for medium-sized arrays where O(n log n) algorithms (like Merge Sort) are too heavy.
  • Useful in embedded systems where memory is limited (due to in-place sorting).
  • Sometimes used as a subroutine in hybrid algorithms.

Advantages

  • In-place Sorting: Requires only O(1) extra space.
  • Faster than Insertion Sort: Especially for larger arrays.
  • Easy to Implement: Straightforward improvement over Insertion Sort.

Disadvantages

  • Not Stable: Does not maintain the order of equal elements.
  • Performance depends on gap sequence: Bad choices can lead to O(n²).
  • Slower than advanced algorithms: Merge Sort, Quick Sort, and Tim Sort usually outperform it on large datasets.
Comment
Article Tags:
Article Tags: