The single idea learners must own before anything else: a pass carries the largest element to the end.
Bubble sort walks left to right, comparing each pair of neighbours. If the left one is bigger, swap. That is the whole rule. One full walk is a pass.[1]
The payoff of one pass: whatever the largest value is, it gets picked up and carried all the way to the last slot. That single fact is the seed of the correctness argument you will teach in Lesson 2.[2]
Press Next comparison and say out loud, before pressing, whether it will swap.
function onePass(a: number[]): boolean {
let swapped = false;
for (let j = 0; j < a.length - 1; j++) {
if (a[j] > a[j + 1]) {
[a[j], a[j + 1]] = [a[j + 1], a[j]];
swapped = true;
}
}
return swapped;
}
Do these from memory. No scrolling up.
[3, 9, 2, 7, 1] and check with the visualizer by editing data-values.Read the "Analysis" and "Optimizing bubble sort" sections of Wikipedia: Bubble sort, then step through VisuAlgo once at slow speed.
Anything unclear? Ask your teaching agent - it wrote this lesson and can go deeper on any point.