Lesson 20 +35 XP

Exchange Sorts: Bubble Sort, Quick Sort & Merge Sort

Exchange Sorts: Bubble Sort, Quick Sort & Merge Sort

Quick Sort vs Merge SortQuick Sort vs Merge Sort

1. Bubble Sort (Standard & Flag-Modified)

Compares adjacent pairs a[j] and a[j + 1], swapping whenever out of order so the largest unsorted key "bubbles" to its final position on each pass:

  • Flag-Modified Optimization: Track int swapped = 0; in each pass. If a pass finishes with swapped == 0, the array is already sorted-terminate early!
  • Best Case (flagged, sorted): O(n) | Avg / Worst: O(n2) | Space: O(1) | Stable: Yes.
C
void bubbleSort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int swapped = 0;
        for (int j = 0; j < n - 1 - i; j++) {
            if (a[j] > a[j + 1]) {
                int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
                swapped = 1;
            }
        }
        if (!swapped) break;
    }
}

2. Quick Sort (Divide &amp; Conquer Exchange Sort)

Selects a pivot, partitions the array so elements ≤ pivot sit on the left and &gt; pivot sit on the right, then recursively sorts both partitions:

  • Pivot Selection Strategies: First element, Last element, Random pivot, or Median-of-Three (median of low, mid, high - eliminates O(n2) behavior on sorted inputs!).
  • Best / Avg: T(n) = 2T(n/2) + n ⇒ O(n log n).
  • Worst Case (unbalanced 0 vs n-1 split): T(n) = T(n-1) + n ⇒ O(n2).
  • Space: O(log n) call stack | Stable: No.
C
int partition(int a[], int low, int high) {
    int pivot = a[high], i = low - 1;
    for (int j = low; j < high; j++) {
        if (a[j] <= pivot) {
            i++;
            int t = a[i]; a[i] = a[j]; a[j] = t;
        }
    }
    int t = a[i + 1]; a[i + 1] = a[high]; a[high] = t;
    return i + 1;
}

3. Merge Sort (Divide &amp; Conquer)

Recursively splits the array into two halves until size 1, then merges two sorted subarrays into a sorted result:

  • Best / Avg / Worst: O(n log n) | Space: O(n) auxiliary array | Stable: Yes.
  • Best for Linked Lists: Merging linked lists requires O(1) pointer re-linking and zero random access!

4. Complete Sorting Comparison Table

AlgorithmBestAverageWorstSpaceStable
Insertion SortO(n)O(n2)O(n2)O(1)Yes
Selection SortO(n2)O(n2)O(n2)O(1)No
Bubble Sort (Flagged)O(n)O(n2)O(n2)O(1)Yes
Shell Sort (Knuth)O(n log n)O(n1.3)O(n3/2)O(1)No
Heap SortO(n log n)O(n log n)O(n log n)O(1)No
Quick SortO(n log n)O(n log n)O(n2)O(log n)No
Merge SortO(n log n)O(n log n)O(n log n)O(n)Yes

Bubble Sort Pass-by-Pass (9 2 5 4 7 8)

PassArray after the passSwaps made
12 5 4 7 8 99 bubbles to the end (5 swaps)
22 4 5 7 8 95↔4
32 4 5 7 8 9none → the flag stops the sort early

Without the flag, the total number of comparisons is (n-1) + (n-2) + … + 1 = (n(n-1) / 2) = 15 for n = 6, which is O(n2).

Quick Sort: The Notes' Partition (pivot = first element)

C
int partition(int a[], int p, int r) {
    int x = a[p];              /* pivot */
    int i = p, j = r + 1, t;
    while (1) {
        do i++; while (i <= r && a[i] < x);   /* stop at an element >= pivot */
        do j--; while (a[j] > x);             /* stop at an element <= pivot */
        if (i >= j) break;
        t = a[i]; a[i] = a[j]; a[j] = t;      /* swap the out-of-place pair */
    }
    t = a[p]; a[p] = a[j]; a[j] = t;          /* put the pivot in its final place */
    return j;
}
void quickSort(int a[], int p, int r) {
    if (p < r) {
        int q = partition(a, p, r);
        quickSort(a, p, q - 1);
        quickSort(a, q + 1, r);
    }
}

Trace on 25 57 48 37 12 92 86 33:

Call (range)PivotArray after partition
0-72512 25 48 37 57 92 86 33
2-74812 25 33 37 48 92 86 57
2-33312 25 33 37 48 92 86 57
5-79212 25 33 37 48 57 86 92
5-65712 25 33 37 48 57 86 92

In the first call, i stops at 57 and j stops at 12; they are swapped; then i stops at 48 (index 2) and j at 12 (index 1), they have crossed, so the pivot 25 is swapped with a[1].

Median-of-Three Pivot (notes' example)

For S = {6, 1, 4, 9, 0, 3, 5, 2, 7, 8}: first = 6, middle = a[⌊(0 + 9)/2⌋] = a[4] = 0, last = 8. The median of {6, 0, 8} is 6, so 6 is the pivot. This avoids the O(n2) worst case on already-sorted input, where &quot;first element&quot; would always be the smallest.

Merge Sort: Code and Trace

C
void merge(int a[], int lo, int mid, int hi) {
    int tmp[100], i = lo, j = mid + 1, k = 0;
    while (i <= mid && j <= hi)
        tmp[k++] = (a[i] <= a[j]) ? a[i++] : a[j++];  /* <= keeps it stable */
    while (i <= mid) tmp[k++] = a[i++];
    while (j <= hi)  tmp[k++] = a[j++];
    for (k = 0; k < hi - lo + 1; k++) a[lo + k] = tmp[k];
}
void mergeSort(int a[], int lo, int hi) {
    if (lo < hi) {
        int mid = (lo + hi) / 2;
        mergeSort(a, lo, mid);
        mergeSort(a, mid + 1, hi);
        merge(a, lo, mid, hi);
    }
}

Trace on 38 27 43 3 9 82 10:

TEXT
               [38 27 43 3 9 82 10]          mid = (0 + 6)/2 = 3
              /                    \
       [38 27 43 3]             [9 82 10]
        /        \               /     \
   [38 27]     [43 3]        [9 82]    [10]
    /   \       /   \         /  \
  [38] [27]   [43]  [3]     [9]  [82]
merge:  [27 38]   [3 43]      [9 82]
        [3 27 38 43]          [9 10 82]
final:  [3 9 10 27 38 43 82]

The recurrence T(n) = 2T(n/2) + n gives O(n log n) in every case, with O(n) extra space for the temporary array.

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Explain Quick Sort with its partition() algorithm. Discuss Best, Average, and Worst case complexities. (10 Marks)
  • Write: Divide &amp; Conquer strategy, partition() C code, median-of-three pivot optimization, O(n log n) vs O(n2) recurrences, and O(log n) stack space.
  • Q2. Compare Quick Sort and Merge Sort. Why is Merge Sort preferred for Linked Lists? (5 Marks)
  • Write: Full complexity/stability/space comparison table, and explain O(1) pointer re-linking without random access in Linked Lists.