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
Type
Data location
Example use
Internal sort
All data fits in main memory (RAM)
Sorting an array of 10,000 marks
External sort
Data is too large for memory and stays on disk; it is sorted in chunks and merged
Sorting 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, passesdata = [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}")
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=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 2fixed : 1 2 3
Key takeaways
Internal sorts work in main memory; external sorts handle data on disk.
Bubble sort: after pass i, the i largest elements are in place.
Comparisons: (n−1)2 (version 1), 2n(n−1) (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).
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Trace bubble sort (version 3) on [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.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-211/complexity-analysis-of-simple-algorithms/sorting-bubble-sort-and-its-analysis/ to read this page.