SUNY Geneseo Department of Computer Science


Designing and Analyzing Bubble Sort, Part 2

{Date}

CSci 141, Spring 2005
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Misc

Hand out Lab 9

Hand out Homework 1

Questions?

How to bubble smallest item to front of list instead of largest to end in "findSmallestAndPutAtFront?"

[Compare-and-Swap Before Recursion vs After]

Algorithm Design and Analysis Example

Problem: sort a list

(Precondition: all items in the list are comparable using "<", ">")

Solution idea: "bubble sort"

    // In a SortableList subclass of List...
    sort()
        if ( ! this.isEmpty() )
            this.findSmallestAndPutAtFront()
                //postcondition: smallest item in list is at head
            this.getRest().sort()

    findSmallestAndPutAtFront()
        if ! this.isEmpty() && ! this.getRest().isEmpty()
            this.getRest().findSmallestAndPutAtFront()
            if this.getRest().first() < this.first()
                temp = this.getAndRemove()
                this.addItem( this.getAndRemove() )
                this.getRest().addItem( temp )

(Notice that the 2nd line of the swap code above turns out to be unnecessary -- the first "getAndRemove" also makes the original second item first)

Be careful about the list operations you use to swap...

[A Swap that Duplicates the Second Item]

Correctness of findSmallestAndPutAtFront

In Java, (most) objects handle...

        a.compareTo( b )

How fast is bubble sort, in terms of list length, n?


Next Lecture