Data Structures and Algorithms • C# examples
Bubble Sort
Understand adjacent swaps and why a simple quadratic sort is mainly educational.
Concept
Bubble sort compares neighboring values and swaps them when out of order. After one pass, the largest remaining value reaches the end of the unsorted region. An early-exit flag avoids repeated passes when input is already sorted, but the algorithm remains unsuitable for large general-purpose datasets.
How to approach it
Shrink the unsorted suffix after each pass and stop when a pass makes no swaps.
Complexity
Worst O(n²), best O(n) with early exit, O(1) extra space.
C# example
for (int end = values.Length - 1; end > 0; end--)
{
bool swapped = false;
for (int i = 0; i < end; i++)
if (values[i] > values[i + 1])
{
(values[i], values[i + 1]) = (values[i + 1], values[i]);
swapped = true;
}
if (!swapped) break;
}
Expected result or behavior
The adjacent swaps place the values in ascending order.
Practice exercise
Count comparisons for reverse-sorted input and compare with merge sort’s growth.
Key takeaway: Simple sorting algorithms teach invariants, but production code should use a library sort.