MCS-211 · Block 1 Unit 3

Complexity Analysis of Simple Algorithms

Section 7 of 8

Block 1 · Unit 3Complexity Analysis of Simple Algorithms11 min · Section 7 of 8

3.7Sorting: Bubble Sort and Its Analysis

Covers IGNOU MCS-211 §3.4.6

Sorting arranges data in order, which makes searching, merging and reporting much easier. This page introduces internal and external sorting, traces bubble sort carefully, and analyses three versions of it — correcting several mistakes in the study material’s versions.

Internal and external sorting

TypeData locationExample use
Internal sortAll data fits in main memory (RAM)Sorting an array of 10,000 marks
External sortData is too large for memory and stays on disk; it is sorted in chunks and mergedSorting a 500 GB log file

To measure a sorting algorithm we count two operations: comparisons of keys and exchanges (swaps) of elements. When records are large, swaps can be the more expensive of the two.

Bubble sort

Python · bubble_trace.py
def bubble(a, version, show=False):
    """version 1: n-1 full passes; 2: shrinking passes; 3: shrinking + flag."""
    a = list(a)
    n = len(a)
    comps = swaps = passes = 0
    for i in range(1, n):
        last = n - 1 if version == 1 else n - i      # j runs 0 .. last-1
        swapped = False
        for j in range(last):
            comps += 1
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swaps += 1
                swapped = True
        passes += 1
        if show:
            print(f"  after pass {i}: {a}")
        if version == 3 and not swapped:
            break
    return a, comps, swaps, passes

data = [23, 18, 15, 37, 8, 11]
print("version 2 on", data)
bubble(data, 2, show=True)
print()
for name, inp in [("given", data), ("sorted", sorted(data)), ("reverse", sorted(data, reverse=True))]:
    for v in (1, 2, 3):
        _, c, s, p = bubble(inp, v)
        print(f"{name:7} v{v}: comparisons = {c:2}, swaps = {s:2}, passes = {p}")
Output
version 2 on [23, 18, 15, 37, 8, 11]
  after pass 1: [18, 15, 23, 8, 11, 37]
  after pass 2: [15, 18, 8, 11, 23, 37]
  after pass 3: [15, 8, 11, 18, 23, 37]
  after pass 4: [8, 11, 15, 18, 23, 37]
  after pass 5: [8, 11, 15, 18, 23, 37]

given   v1: comparisons = 25, swaps = 11, passes = 5
given   v2: comparisons = 15, swaps = 11, passes = 5
given   v3: comparisons = 15, swaps = 11, passes = 5
sorted  v1: comparisons = 25, swaps =  0, passes = 5
sorted  v2: comparisons = 15, swaps =  0, passes = 5
sorted  v3: comparisons =  5, swaps =  0, passes = 1
reverse v1: comparisons = 25, swaps = 15, passes = 5
reverse v2: comparisons = 15, swaps = 15, passes = 5
reverse v3: comparisons = 15, swaps = 15, passes = 5

Three versions

VersionInner loopComparisonsBest caseWorst case
1always j=0…n−2j = 0 \dots n-2, for n−1n - 1 passes(n−1)2(n-1)^2Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)
2pass ii uses j=0…n−i−1j = 0 \dots n-i-1 (skips the sorted end)(n−1)+(n−2)+⋯+1=n(n−1)2(n-1) + (n-2) + \dots + 1 = \frac{n(n-1)}{2}Θ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)
3version 2 + stop after a pass with no swapsbetween n−1n - 1 and n(n−1)2\frac{n(n-1)}{2}Θ(n)\Theta(n) (sorted input)Θ(n2)\Theta(n^2) (reverse input)

The number of swaps is the same in all three versions on the same input: each swap fixes exactly one pair of elements that is in the wrong order (an inversion), and the sorted end is never touched by a swap. For n=6n = 6: 25, 15 and 15 comparisons, but 11 swaps in every version for the given data.

C · flag_inside.c
#include <stdio.h>

/* Version 3 with the flag test INSIDE the inner loop, as printed. */
void bubble_printed(int A[], int n)
{
    for (int i = 1; i <= n - 1; i++) {
        int flag = 0;
        for (int j = 0; j <= n - i - 1; j++) {
            if (j + 1 < n && A[j] > A[j + 1]) {
                int t = A[j]; A[j] = A[j + 1]; A[j + 1] = t;
                flag = 1;
            }
            if (flag == 0)
                return;              /* stops at the first in-order pair */
        }
    }
}

/* Corrected: test the flag after the whole pass. */
void bubble_fixed(int A[], int n)
{
    for (int i = 1; i <= n - 1; i++) {
        int flag = 0;
        for (int j = 0; j < n - i; j++) {
            if (A[j] > A[j + 1]) {
                int t = A[j]; A[j] = A[j + 1]; A[j + 1] = t;
                flag = 1;
            }
        }
        if (flag == 0)
            return;
    }
}

void show(const char *label, const int A[], int n)
{
    printf("%s", label);
    for (int i = 0; i < n; i++)
        printf(" %d", A[i]);
    printf("\n");
}

int main(void)
{
    int p[] = {1, 3, 2}, f[] = {1, 3, 2};
    bubble_printed(p, 3);
    bubble_fixed(f, 3);
    show("printed:", p, 3);
    show("fixed  :", f, 3);
    return 0;
}
Output
printed: 1 3 2
fixed  : 1 2 3

Key takeaways

  • Internal sorts work in main memory; external sorts handle data on disk.
  • Bubble sort: after pass ii, the ii largest elements are in place.
  • Comparisons: (n−1)2(n-1)^2 (version 1), n(n−1)2\frac{n(n-1)}{2} (versions 2, 3 in the worst case); swaps are the same in all versions.
  • The flag must be tested after a whole pass; it improves only the best case to Θ(n)\Theta(n).

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

What is the array after pass 1 of bubble sort on [5,1,4,2,8][5, 1, 4, 2, 8]?

Show answer

Answer: B. [1,4,2,5,8][1, 4, 2, 5, 8] with 3 swaps, 4 comparisons

5↔1, 5↔4, 5↔2 are swaps, and 5 vs 8 is not: 4 comparisons and 3 swaps give [1, 4, 2, 5, 8]. The fully sorted array needs another pass.

Question 2 · multiple choice

How many comparisons does version 2 make on any input of 8 elements?

Show answer

Answer: C. 28

7 + 6 + … + 1 = 8 × 7 / 2 = 28. 49 = (n − 1)² is version 1.

Question 3 · multiple choice

Version 3 (flag checked after each pass) on an already sorted array of 10 elements makes:

Show answer

Answer: A. 9 comparisons

One pass of n − 1 = 9 comparisons finds no swaps, and the algorithm stops. 45 is the worst case.

Question 4 · multiple choice

Compared with version 1, version 2 of bubble sort reduces:

Show answer

Answer: B. the number of comparisons

Version 2 skips the sorted end, where no swaps ever happen, so only comparisons drop (25 → 15 for n = 6); swaps stay 11.

Question 5 · multiple choice

What is the worst-case time complexity of bubble sort with the early-exit flag?

Show answer

Answer: C. Θ(n2)\Theta(n^2)

On reverse-sorted input every pass swaps, so all passes run: n(n − 1)/2 comparisons. Θ(n) is the best case only.

Question 6 · short answer

Trace bubble sort (version 3) on [4,3,2,1][4, 3, 2, 1], giving the array after each pass and the total comparisons and swaps.

Show worked answer

Pass 1 (3 comparisons): [3, 2, 1, 4] with 3 swaps. Pass 2 (2 comparisons): [2, 1, 3, 4] with 2 swaps. Pass 3 (1 comparison): [1, 2, 3, 4] with 1 swap. Every pass swapped, so all 3 passes ran: 6 comparisons = 4 × 3 / 2, and 6 swaps (the number of inverted pairs). This is the worst case.

↑ ↓ move↵ openTab switch type