CS 162 Spring 2004
Programming Assignment 5

Sorting

Due: Wednesday, May 19th

Once again we are going to write an application that reads from and writes to the console input. (Makes the TA's life easier). In this assignment you going to write an application that sorts an array of numbers. An example input and the corresponding output is shown below. However, in your application you can assume that the input is presented one integer per line until end of input is encountered.

0 1 2 3 4 5 6 7 8 9 10
8 5 4 9 1 7 6 10 3 2 0
The first line represents the input (only it would be one number per line) and the second line is the output (again, you would produce it one number per line). I'll leave for a moment the discussion of how it is determined that one number is less than another.

The main program for your assignment should be in a class named WordSort. When started, the application should read numbers from the standard input, one number per line, and place them into a Vector (or ArrayList) of Integer values. (That's the wrapper class Integer, not the primitive int). You can use the fact that Vectors and ArrayLists increase their size automatically as values are added, so you do not need to know the number of elements ahead of time. This time, unlike programming assignment 4, the input need not necessarily be a valid integer. Use Integer.parseInt or Integer.valueOf to convert the string into a number. If this method returns an exception you must trap the exception and not add the number to your collection. You should then continue reading numbers with the next line.

Then you must write a sorting algorithm that will sort this arrray. You must use either a MergeSort or a QuickSort, both of which are described in Chapter 18 of the text. Once the values are sorted, write them back to the standard output. The output should be just the number, one number per line, no extra spaces.

To compare two values, you must create an Comparator object, as described in Section 18.8. The Comparator interface is found in java.util.

And how are items to be compared? Have you figured out the order described in the first paragraph yet? One number is less than another if their textual description would come before the other in dictionary order. You know from the previous assignment how to convert a number into a textual description. You can use the compare function in class String to determine dictionary order. If you look at the output shown, you will see that they are listed in this order.