Insertion sort is simple and fast on nearly sorted data, but slow on badly ordered data, because each item can only move one place at a time. Shell sort, invented by Donald Shell in 1959, fixes this by first comparing items that are far apart, so they can jump long distances early. Bucket sort takes a different approach: it drops values into ranges, sorts each small range, then joins them. On evenly spread data it runs in about O(n) time.
In this lesson you will learn
- How shell sort uses shrinking gaps
- Why the final pass of shell sort is fast
- How gap sequences affect the running time
- How bucket sort splits values into ranges
- When bucket sort works well, and when it does not
You should know basic sorting algorithms and counting sort and radix sort.
Shell Sort
#include <stdio.h>
void print(const char *label, const int *a, int n) {
printf("%-14s", label);
for (int i = 0; i < n; i++) printf("%3d", a[i]);
printf("\n");
}
/* Shell sort: insertion sort on elements 'gap' apart, with shrinking gaps.
Large gaps move far-away items quickly; the final gap of 1 is a normal
insertion sort on an almost-sorted array, which is fast. */
long shellSort(int *a, int n, int verbose) {
long moves = 0;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int x = a[i], j = i;
while (j >= gap && a[j - gap] > x) { a[j] = a[j - gap]; j -= gap; moves++; }
a[j] = x;
}
if (verbose) { char label[32]; snprintf(label, sizeof label, "after gap %d:", gap); print(label, a, n); }
}
return moves;
}
long insertionSort(int *a, int n) {
long moves = 0;
for (int i = 1; i < n; i++) {
int x = a[i], j = i;
while (j > 0 && a[j - 1] > x) { a[j] = a[j - 1]; j--; moves++; }
a[j] = x;
}
return moves;
}
int main(void) {
int a[] = { 95, 83, 18, 53, 69, 17, 62, 7, 47, 28, 25, 86 };
int n = sizeof a / sizeof a[0];
print("start:", a, n);
shellSort(a, n, 1);
/* Compare the work on a reversed array of 2000 numbers */
enum { BIG = 2000 };
static int x[BIG], y[BIG];
for (int i = 0; i < BIG; i++) x[i] = y[i] = BIG - i;
printf("\nreversed %d items: insertion sort moves %ld, shell sort moves %ld\n",
BIG, insertionSort(x, BIG), shellSort(y, BIG, 0));
return 0;
}
Output
start: 95 83 18 53 69 17 62 7 47 28 25 86
after gap 6: 62 7 18 28 25 17 95 83 47 53 69 86
after gap 3: 28 7 17 53 25 18 62 69 47 95 83 86
after gap 1: 7 17 18 25 28 47 53 62 69 83 86 95
reversed 2000 items: insertion sort moves 1999000, shell sort moves 10400
- Shell sort runs insertion sort on items that are
gappositions apart. With 12 items, the gaps are 6, 3 and 1. - With gap 6, item 0 is compared with item 6, item 1 with item 7, and so on. The large 95 jumps from the front to position 6 in one move.
- Each pass leaves the array more ordered. The last pass, with gap 1, is a normal insertion sort, but the array is almost sorted by then, so it needs few moves.
- On 2,000 numbers in reverse order, insertion sort makes 1,999,000 moves. Shell sort makes 10,400.
- Shell sort sorts in place with O(1) extra memory and is not stable: equal items can change their order.
| Gap sequence | Example gaps | Worst-case time |
|---|---|---|
| Shell’s original (n/2, n/4, …) | 500, 250, 125, … | O(n2) |
| Knuth (3h + 1) | 1, 4, 13, 40, 121, … | O(n1.5) |
| Ciura (found by experiment) | 1, 4, 10, 23, 57, 132, 301, 701 | Not proven; very fast in practice |
Bucket Sort
#include <stdio.h>
#include <stdlib.h>
#define BUCKETS 5
/* Bucket sort for values spread evenly in [0, 1): marks given as fractions */
typedef struct Node { double v; struct Node *next; } Node;
/* Insert into a bucket's linked list in sorted order (insertion sort) */
void insertSorted(Node **head, double v) {
Node *n = malloc(sizeof *n);
if (!n) { perror("malloc"); exit(1); }
n->v = v;
while (*head && (*head)->v < v) head = &(*head)->next;
n->next = *head;
*head = n;
}
void bucketSort(double *a, int n) {
Node *bucket[BUCKETS] = { NULL };
for (int i = 0; i < n; i++) {
int b = (int)(a[i] * BUCKETS); /* 0.00-0.19 -> 0, 0.20-0.39 -> 1, ... */
insertSorted(&bucket[b], a[i]);
}
int k = 0;
for (int b = 0; b < BUCKETS; b++) { /* join the buckets in order */
printf("bucket %d [%.1f, %.1f): ", b, (double)b / BUCKETS, (double)(b + 1) / BUCKETS);
for (Node *p = bucket[b]; p; ) {
printf("%.2f ", p->v);
a[k++] = p->v;
Node *nx = p->next; free(p); p = nx;
}
printf("\n");
}
}
int main(void) {
double marks[] = { 0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68, 0.55, 0.41 };
int n = sizeof marks / sizeof marks[0];
bucketSort(marks, n);
printf("sorted: ");
for (int i = 0; i < n; i++) printf("%.2f ", marks[i]);
printf("\n");
return 0;
}
Output
bucket 0 [0.0, 0.2): 0.12 0.17
bucket 1 [0.2, 0.4): 0.21 0.23 0.26 0.39
bucket 2 [0.4, 0.6): 0.41 0.55
bucket 3 [0.6, 0.8): 0.68 0.72 0.78
bucket 4 [0.8, 1.0): 0.94
sorted: 0.12 0.17 0.21 0.23 0.26 0.39 0.41 0.55 0.68 0.72 0.78 0.94
- The values are fractions from 0 up to 1, such as marks out of 100 divided by 100. With 5 buckets,
(int)(value * 5)picks the bucket: 0.00–0.19 go to bucket 0, 0.20–0.39 to bucket 1, and so on. - Each bucket is a linked list kept in order as values arrive, which is insertion sort on a small list.
- Reading the buckets from first to last gives the sorted result.
- If the values are spread evenly, each bucket holds only a few items, and the total time is about O(n + k) for n items and k buckets.
- If most values land in one bucket, bucket sort becomes insertion sort on that bucket: O(n2) in the worst case.
| Algorithm | Average time | Extra memory | Stable |
|---|---|---|---|
| Insertion sort | O(n2) | O(1) | Yes |
| Shell sort | Depends on gaps, roughly O(n1.3) in practice | O(1) | No |
| Bucket sort (even data) | O(n + k) | O(n + k) | Yes, if buckets keep order |
| Merge sort | O(n log n) | O(n) | Yes |
Common Mistakes
- Using bucket sort on skewed data, such as values that mostly fall in one small range.
- A value of exactly 1.0 in bucket sort gives bucket index
k, which is out of range. Clamp it tok - 1. - Forgetting the final gap of 1 in shell sort, which leaves the array not fully sorted.
- Assuming shell sort is stable. Long jumps can reorder equal items.
Practice Exercises
Exercise 1. Change shellSort to use Knuth’s gaps (1, 4, 13, 40, …).
Show answer
int gap = 1;
while (gap < n / 3) gap = 3 * gap + 1; /* first gap of 1, 4, 13, ... that reaches n/3 */
for (; gap > 0; gap = (gap - 1) / 3) {
/* same gapped insertion sort as before */
}
Exercise 2. Exam marks are whole numbers from 0 to 100. How would you use bucket sort with 10 buckets?
Show answer
Use bucket mark / 10 for marks 0 to 99, and put 100 in bucket 9 as a special case. Each bucket holds one band of marks: 0–9, 10–19, and so on.
Frequently Asked Questions
Is shell sort used today?
Sometimes. It needs no extra memory and only a few lines of code, so it appears in small embedded systems. Most standard libraries use faster general-purpose sorts such as introsort or Timsort.
How is bucket sort different from counting sort?
Counting sort has one bucket for every possible value and just counts them. Bucket sort groups a range of values into each bucket, so it also works for fractions and very wide ranges, but each bucket must still be sorted.
Summary
- Shell sort runs insertion sort with shrinking gaps, so items can move far early on.
- The gap sequence decides its speed; good sequences are much faster than O(n2).
- Bucket sort splits values into ranges, sorts each and joins them.
- Bucket sort is about O(n) on evenly spread data but slow on clustered data.
Next: Meet in the Middle in C.
