**Unformatted text preview: **osition max There are n1 phases
During a phase, what happens?
A nested FOR loop is executed
The nested loop moves from 1 to max
and does a swap if necessary
Let’s look at an example with n = 4 Bubble Sort
Bubble Sort
FOR max = n1 downto 1
FOR left = 1 upto max
right = left + 1
IF M(left) > M(right) THEN swap them
max = 3
IF M(1) > M(2) swap them
IF M(2) > M(3) swap them
IF M(3) > M(4) swap them
max = 2
IF M(1) > M(2) swap them
IF M(2) > M(3) swap them
max = 1 IF M(1) > M(2) swap them make a pass up to position max Now we can see the effect of the inner loop for each “version” of the outer loop… …and the overall effect of the nested loops Correctness
Correctness Why does it work? After first pass, the largest is in position n 2nd pass, the 2nd largest is in position n1 3rd pass, the 3rd largest is in position n2 etc. nth pass, the nth largest is in position 1 Running time
Running time Count comparisons Don’t get bogged down in detail Iteration is the biggest contributor Bubble Sort: (n1) + (n2) + … + 2 + 1 = n(n1)/2
= (...

View
Full
Document