Sorting
Bubble Sort
Repeatedly walk the array comparing adjacent pairs and swapping any that
are out of order. After pass k, the k largest elements are in their
final positions at the end. Early-exit when a pass makes zero swaps.
Algorithm
Canonical input from the lesson spec is [5, 1, 4, 2, 8]. Three passes
sort the array; pass three triggers the early exit.
Basic Implementation
basic.dart
void main() {
final arr = <int>[5, 1, 4, 2, 8];
final n = arr.length;
for (var i = 0; i < n - 1; i++) {
var swapped = false;
for (var j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
final tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
swapped = true;
}
}
if (!swapped) {
break;
}
}
print(arr);
}
Complexity
- Time: O(n^2) worst and average, O(n) best with early exit
- Space: O(1)
- Stable: yes
Implementation notes
- Dart: write the two explicit loops and the
swappedflag. Do not callarr.sort(); it would hide the comparison-and-swap mechanics the lesson is teaching. - The replay shows the compared pair on each frame and the post-swap array, matching the lesson spec's per-pass tables.
adjacent swap
Swap neighbouring out-of-order pairs.
early termination
A pass with zero swaps means the array is already sorted.