Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: osition max There are n­1 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 = n­1 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 n­1 3rd pass, the 3rd largest is in position n­2 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: (n­1) + (n­2) + … + 2 + 1 = n(n­1)/2 = (...
View Full Document

This document was uploaded on 04/02/2014.

Ask a homework question - tutors are online