import CursoredList; import ListCursor; /** * Strange static stuff from question A on exam 3 of CSC152 2000S. * * @author Hermione Hacker * @author Herman Hacker * @author Herr Doktor Professor Rebelsky * @version 1.0 of April 2000. */ public class CursoredListSorter { /** * Sort a cursored list, comparing things as strings. * Uses the selection sort algorithm. */ public static void sort(CursoredList list) { // Create a cursor. This is the destination of each swap. ListCursor current = list.newCursor(); // A second cursor identifies the smallest known element // of the list. ListCursor smallest; // Start at the beginning current.reset(); // For each position in the list ... while (current.inList()) { // Find the smallest element in the sublist. smallest = findSmallest(list,current); // DEBUG // System.err.println("Smallest: " + // list.valueAt(smallest)); // Swap the contents at the two positions. list.swap(current,smallest); // And move on. current.advance(); } // while still in the list } // sort(CursoredList) /** * Put a cursor on the location of the smallest element * in a sublist that starts at a particular cursor. Uses * string comparison to identify the proper place for an * element. * Pre: The sublist is nonempty. * Post: Does not move the starting cursor. */ protected static ListCursor findSmallest(CursoredList list, ListCursor start) { // Our guess as to the smallest. ListCursor guess = start.makeCopy(); // The string that corresponds to that guess. String guessString = list.valueAt(guess).toString().toLowerCase(); // A cursor we can use to iterate through the list. Start // it at the next element. ListCursor temp = start.makeCopy(); temp.advance(); // System.err.println(" First guess: " + guessString); // DEBUG // For each remaining position in the list while (temp.inList()) { // Get the contents. String tempString = list.valueAt(temp).toString().toLowerCase(); // System.err.println(" Next guess: " + tempString); // DEBUG // If it's smaller, update our guess. if (tempString.compareTo(guessString) < 0) { guess.moveTo(temp); guessString = tempString; } // if it's smaller. // Move on to the next thing temp.advance(); } // while // That's it, we're done. return guess; } // findSmallest } // class CursoredListSorter