SUNY Geneseo Department of Computer Science
{Date}
CSci 141, Spring 2005
Prof. Doug Baldwin
Hand out Lab 9
Hand out Homework 1
How to bubble smallest item to front of list instead of largest to end in "findSmallestAndPutAtFront?"
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...
Correctness of findSmallestAndPutAtFront
In Java, (most) objects handle...
a.compareTo( b )
How fast is bubble sort, in terms of list length, n?