November 16

Lecture Overview

Introduction to Algorithms.

Selection Sort

Here is selection sort as an example of the above points. Selection sort has the following pseudocode (Note that python and pseudocode are very similar and this isn't an accident; pseudocode is old and when the python developers were designing the language they used pseudocode as an inspiration.)

1
2
3
4
5
6
7
8
9
10
11
12
for i in 0 to L.length - 1
    # Find the smallest element among positions i to L.length-1
    min_idx = i
    for j in i+1 to L.length - 1
        if L[j] < L[min_idx]
           min_idx = j
       endif
    endfor

   # move the smallest found into position i
   swap L[i] with L[min_idx]
endfor

Informal Proof of Correctness

Selection sort works by progressively making the slice L[0...i] of the list the i-th smallest elements in sorted order (recall that list slicing is up to but not including the top index) until the entire list is sorted. So say L[0...i] is the i-smallest elements in sorted order and we want to extend this to L[0..(i+1)]. What we need to do is search all the elements from i to the end of the list and find the smallest among them. Whatever element is found to be the smallest is moved into position. The body of the loop over i carries out this task: it first finds the smallest element (lines 3-8) and then swaps the smallest found into position (line 11). To find the smallest element, we loop over j, comparing the smallest found so far with the element at index j.

An informal argument of the above type is what we do 99% of the time. The above paragraph argued that the algorithm always produces a sorted list no matter the input and while it didn't mention every detail it was (hopefully) enough convince you. We are lazy and only want to explain enough so that we are convinced the algorithm works. This is dangerous because maybe there is an error somewhere in a detail we didn't mention, but we don't notice this because we ignored some details. For newbies to these types of proof, it is very hard to know when a detail should be left out or if it needs to be explained. One detail which was omitted is why the loop over j can start at i+1 instead of i.

Formal Proof of Correctness

For comparison, here is a more formal proof of correctness. It mentions more details and so you can be more certain there is no error that you have overlooked, but it is more work to both write and read. The proof of correctness works via loop invariants, which are statements which are true throughout every iteration of the loop.

Speed

I show how we estimate the speed of this algorithm next time.

Exercises