Loading lessons...
Sorting Concepts, Insertion, Shell, Selection & Heap Sort
Sorting Concepts, Insertion, Shell, Selection & Heap Sort
Sorting is the process of rearranging a collection of records into ascending or descending order of a sort key.
1. Fundamental Sorting Concepts
- Internal vs External Sorting: Internal sorts keep all data in main memory (RAM); External sorts handle massive files on disk/tape using multi-way merging.
- In-Place vs Out-of-Place: An in-place sort uses O(1) (or O(log n) stack) extra memory.
- Stability: A sorting algorithm is stable if records with equal keys retain their original relative order. (Example: Sorting student records by test score after already sorting alphabetically by name preserves alphabetical order among ties!)
- Adaptivity: An adaptive sort runs faster when the input is already partially sorted.
2. Insertion Sort & Shell Sort
- Straight Insertion Sort: Divides the array into a sorted prefix and unsorted suffix; takes each next element (
key) and shifts larger elements right to insertkeyinto its proper spot (just like sorting playing cards in hand). - Trace on
[23, 78, 45, 8, 32]:[23, 78]→[23, 45, 78]→[8, 23, 45, 78]→[8, 23, 32, 45, 78]. - Best Case (sorted): O(n) | Average / Worst (reverse-sorted): O(n2) | Space: O(1) | Stable: Yes | Adaptive: Yes.
- Shell Sort (Diminishing Increment Sort): Generalizes insertion sort by comparing elements separated by a gap h (moving distant out-of-order elements quickly), then shrinking h down to 1 (final pass is fast insertion sort on nearly-sorted data).
- With Knuth's gap sequence (h = 3h + 1:
1, 4, 13, 40, ...), worst-case improves to O(n3/2)! Stable: No.
3. Selection Sort & Heap Sort
- Straight Selection Sort: On pass i, finds the minimum element in
a[i .. n-1]and swaps it witha[i]. - Best / Avg / Worst: O(n2) (not adaptive) | Swaps: at most n - 1 (minimizes memory writes!) | Space: O(1) | Stable: No (standard).
- Heap Sort (Selection via Max-Heap):
- Phase 1 (Build Max-Heap): Heapify bottom-up in O(n).
- Phase 2 (Extract Max): Repeat n - 1 times: swap root
A[0]withA[i], shrink heap size, andreheapDown(0)in O(log n).
- Best / Avg / Worst: O(n log n) | Space: O(1) in-place | Stable: No.
C
void insertionSort(int a[], int n) {
for (int i = 1; i < n; i++) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
void selectionSort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++)
if (a[j] < a[minIdx]) minIdx = j;
int t = a[i]; a[i] = a[minIdx]; a[minIdx] = t;
}
}Insertion Sort: Cost Analysis with tj
TEXT
INSERTION-SORT(A, n) cost times
1 for j = 2 to n c1 n
2 key = A[j] c2 n − 1
3 i = j − 1 c3 n − 1
4 while i > 0 and A[i] > key c4 Σ t_j (j = 2..n)
5 A[i + 1] = A[i] c5 Σ (t_j − 1)
6 i = i − 1 c6 Σ (t_j − 1)
7 A[i + 1] = key c7 n − 1Here tj is the number of times the while test on line 4 runs for that value of j.
- Best case (already sorted): the test fails at once, tj = 1 for every j, so T(n) = an + b - Θ(n).
- Worst case (reverse sorted): key is compared with all j − 1 earlier elements, tj = j, so ∑ tj = (n(n+1) / 2) - 1 and T(n) = an2 + bn + c - Θ(n2).
- Average case: about half the earlier elements are larger, tj ≈ j/2 - still Θ(n2).
Trace on 8 4 6 9 2 3 1 (the sorted part grows from the left):
| j | Array after inserting A[j] |
|---|---|
| 2 (4) | 4 8 6 9 2 3 1 |
| 3 (6) | 4 6 8 9 2 3 1 |
| 4 (9) | 4 6 8 9 2 3 1 |
| 5 (2) | 2 4 6 8 9 3 1 |
| 6 (3) | 2 3 4 6 8 9 1 |
| 7 (1) | 1 2 3 4 6 8 9 |
Shell Sort Worked Example (notes): gaps 5, 2, 1
Array: 46 2 83 41 102 5 17 31 64 49 18 (11 items)
| Gap | Sub-arrays sorted (elements gap apart) | Array after the pass |
|---|---|---|
| 5 | {46, 5, 18} {2, 17} {83, 31} {41, 64} {102, 49} | 5 2 31 41 49 18 17 83 64 102 46 |
| 2 | {5, 31, 49, 17, 64, 46} {2, 41, 18, 83, 102} | 5 2 17 18 31 41 46 83 49 102 64 |
| 1 | ordinary insertion sort on an almost-sorted array | 2 5 17 18 31 41 46 49 64 83 102 |
Choosing the Gap Sequence
- Shell's original: first gap N/2, then keep halving (N = 16 → 8, 4, 2, 1). Simple, but worst case O(n2) because even gaps keep comparing the same positions.
- Odd gaps only: like Shell's, but if the division gives an even number, add 1. Better, because all-odd gaps remove the common factor 2.
- 2.2 method: like the odd-gap method but divide by 2.2 and truncate. Best of the three-the gaps are closest to relatively prime.
- Knuth's sequence: h = 1, 4, 13, 40, 121, 364, 1093, … (h = 3h + 1). Start from the largest h below N and go back down with h = (h − 1)/3. Gives about O(n1.5).
Gap sequences work best when the gaps are relatively prime to each other.
Selection Sort Passes (8 4 6 9 2 3 1)
Each pass finds the minimum of the unsorted part and swaps it to the front:
| Pass | Minimum chosen | Array |
|---|---|---|
| 1 | 1 | 1 4 6 9 2 3 8 |
| 2 | 2 | 1 2 6 9 4 3 8 |
| 3 | 3 | 1 2 3 9 4 6 8 |
| 4 | 4 | 1 2 3 4 9 6 8 |
| 5 | 6 | 1 2 3 4 6 9 8 |
| 6 | 8 | 1 2 3 4 6 8 9 |
Always n(n − 1)/2 = 21 comparisons but at most n − 1 = 6 swaps.
Heap Sort Trace (4 10 3 5 1 8 2)
- Build max heap bottom-up (reheap down from the last internal node): 10 5 8 4 1 3 2.
- Repeatedly swap the root with the last element of the heap and reheap down:
| Step | Heap part | Sorted part |
|---|---|---|
| swap 10 | 8 5 3 4 1 2 | 10 |
| swap 8 | 5 4 3 2 1 | 8 10 |
| swap 5 | 4 2 3 1 | 5 8 10 |
| swap 4 | 3 2 1 | 4 5 8 10 |
| swap 3 | 2 1 | 3 4 5 8 10 |
| swap 2 | 1 | 1 2 3 4 5 8 10 |
🎯 END-TERM EXAM PREP
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What is Stability in sorting? Write C code and trace Straight Insertion Sort on
[23, 78, 45, 8, 32]. (5 Marks) - Write: Stability definition with equal-key student-record example,
insertionSort()C function, pass-by-pass trace, and Best O(n) / Worst O(n2) analysis. - Q2. Explain Shell Sort and Heap Sort with their time and space complexities. (7.5 Marks)
- Write: Diminishing increment gap sequence (h = 3h + 1, O(n3/2)) for Shell Sort; 2-phase Build-Heap O(n) + n Extract-Max O(log n) = O(n log n) in-place for Heap Sort.