FlowLab Logo

Shell Sort Visualizer

SlowFast
515
(8)
Ready to start
33
[0]
10
[1]
67
[2]
13
[3]
11
[4]
82
[5]
44
[6]
57
[7]
Current Element
Comparing
Sorted
Operation Logs
Click "Start Sort" to begin
Algorithm Info
Time Complexity: O(n²) worst case, O(n log n) average with good gap sequences
Space Complexity: O(1) - sorts in place
Stable: No - may change relative order of equal elements
How it works: Uses diminishing gaps to sort elements that are far apart first, then gradually reduces the gap until it becomes 1 (regular insertion sort).
Why efficient: By sorting elements far apart first, it moves elements closer to their final positions quickly, making the final insertion sort pass much faster.
Implementation
function shellSort(arr) {
  const n = arr.length;
  for (let gap = Math.floor(n / 2); gap > 0; gap = Math.floor(gap / 2)) {
    for (let i = gap; i < n; i++) {
      let temp = arr[i], j = i;
      while (j >= gap && arr[j - gap] > temp) {
        arr[j] = arr[j - gap];
        j -= gap;
      }
      arr[j] = temp;
    }
  }
  return arr;
}