Shell Sort
Shell Sort (gap-based insertion) improves insertion sort: group elements by a gap, sort each group by insertion, shrink the gap, and finish with a final insertion sort when gap = 1.
Click "Step forward" to watch the algorithm state change.
- Choose initial gap and group the array.
- Insertion sort within each group.
- Shrink and repeat grouping + sorting.
- When , do a final insertion sort.
Pseudo-code:
for gap = n/2; gap >= 1; gap = gap/2:
for i = gap to n-1:
key = A[i]
j = i - gap
while j >= 0 and A[j] > key:
A[j+gap] = A[j]
j = j - gap
A[j+gap] = key
void ShellSort(int A[], int n) {
// increment sequence: n/2, n/4, ..., 1 (better sequences such as Hibbard's can be used)
for (int gap = n / 2; gap >= 1; gap /= 2) {
// insertion sort within each group
for (int i = gap; i < n; i++) {
int key = A[i];
int j = i - gap;
while (j >= 0 && A[j] > key) {
A[j + gap] = A[j]; // shift the element in the group by gap positions
j -= gap;
}
A[j + gap] = key;
}
}
}
Choosing the Increment Sequence
- A common sequence: (simple, but in the worst case)
- Hibbard’s sequence: , which gives in the worst case
- Sedgewick’s sequence: , which performs even better
The choice of the increment sequence directly affects the efficiency of Shell sort, and it is a subject of research.
- Best:
- Worst: (depends on gap sequence)
- Space:
- Stability: unstable
Exercise 1
Summarize the idea of Shell sort and how it differs from straight insertion sort.
Approach: Grouped insertion, compared with straight insertion sort.
Steps:
- Shell sort inserts by groups first and then shrinks the increment step by step
- Straight insertion sort inserts only one element per pass
Answer: Shell sort inserts by groups, which makes it more efficient.
Exercise 2
What are Shell sort’s time and space complexities?
Approach: Consider the time complexity and the extra space.
Steps:
- Time complexity (best case), (worst case)
- Space complexity
Answer: Time ~, space .
