Statistics
Controls
Summary
Shell Sort is an in-place comparison sort that improves upon Insertion Sort by allowing elements to be moved over larger distances. It works by sorting elements that are far apart first (using a large gap), then progressively reducing the gap. This initial sorting of distant elements, called h-sorting, significantly reduces disorder and the number of shifts required in later stages, making the final passes (with smaller gaps) extremely fast.
How it Works
-
1. Choose a Gap Sequence: Start with a large gap. A common sequence (used in this implementation) is to start with a gap of
n/2, thenn/4, and so on, until the gap is 1. -
2. Perform Gapped Insertion Sort: For the current gap, iterate through the array from the
gap-th element to the end. -
3. Compare and Shift: For each element, compare it with the element
gappositions behind it (i-gap). If the gapped element is larger, shift it forward to the current position. Continue this process, moving backwards bygapeach time, until the correct spot is found. -
4. Insert: Place the current element into the newly opened position.
-
5. Reduce Gap: After sorting the entire array for the current gap, reduce the gap according to the sequence and repeat the process.
-
6. Final Pass: The final pass is always with a gap of 1. At this point, the array is nearly sorted, so a standard Insertion Sort pass finishes the job very efficiently.