SUNY Geneseo Department of Computer Science


Correctness of Bubble Sort in Lists

{Date}

CSci 141, Fall 2004
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Misc

CS Dept. Halloween party

Hand out Lab 8

Questions?

Homework

[Black Tile Leads to Two Treasure Hunts, on Left and Right]

Recursive Bubblesort

Goal: A "SortableList" subclass that handles a "sort" message that makes a list put its elements in ascending order. Assume elements are all ones for which "<" is meaningful.

Strategy: Move the smallest element in the list to the front, by swapping small elements with things in front of them, then recursively sort the tail of the list

    // In class SortableList, a subclass of List...
    void sort() {
        if ! this.isEmpty()
            this.bringSmallestToFront()
            this.getRest().sort()
    }

    void bringSmallestToFront()
        // Postcondition: smallest element in
        //   list is at head
        // Precondition: list is not empty
        if ( this.getRest().isEmpty() )
            do nothing
        else
            this.getRest().bringSmallestToFront()
            if this.getFirst() < this.getRest().getFirst()
                do nothing
            else
                first = this.getAndRemove()
                second = this.getAndRemove()
                this.addItem( first )
                this.addItem( second )

Mini-assignment: build the swapping from primitive list messages

[Swapping 1st and 2nd Elements of a List]

Correctness?

Execution Time?


Next Lecture