Project: Linear-time sorting

The goal of this project is to understand and implement the two great linear-time sorting algorithms, counting sort and radix sort.

Do not attempt this project until you understand counting sort and radix sort. They are not intuitive (until you get them), and although this project description will help you apply the concepts to this particular implementation, it will not help you understand the algorithms if you don't have a good sense of them already.

1. Set up

Make a folder for this project and copy the starter code from the course folder:

cp -r ~tvandrun/Public/cs345/linear-sort/. .

Make a new project in Eclipse. You will find two folders, sorts for the sorting algorithms (both in the class Sorts) and tests for the JUnit tests. CountingSortTest and RadixSortTest are the tests to use for parts 2 and 3, respectively; SortTest contains code shared by the two of them.

2. Counting sort

The version of counting sort that you will implement is generic. It can work on an array of any type. But counting sort requires integers, right? Not a problem; all we need is some way of converting each item in the array into an integer that we can use for the counting part of counting sort. For that purpose, we define an interface ToInteger with a method v(T) that converts generic type T to an int. The method countingSort(), then, takes an array to sort and an object of type ToInteger that indicates how to treat each item in the array as an int

Implement counting sort as five loops (each of them are single loops---no nested loops, each being a single pass over an array):

Test this using CountingSortTest.

3. Radix sort

Radix sort is essentially given to you, just with one line missing. But to fill in that one line, you will need to understand what is in the given code completely. In short, this implementation of radix sort uses your implementation of counting sort, calling it once for each digit (base r). Thus it first calculates the number of digits (that is, the maximum number of digits of any number in the array), and then calls counting sort in a loop based on the number of digits.

Each call to counting sort will sort the given array with respect to one digit. Thus the ToInteger object you pass to counting sort must pick out the appropriate digit from each number. Your task is to finish writing the ToInteger object (as an anonymous inner class). Specifically you must write the body of the method v() that picks out the ith digit from item. (Delete the dummy line return -1;.)

Test this using RadixSortTest.

4. To turn in

Please copy Sorts.java to your turn-in folder /cslab/class/cs345/(your id)/linear-sort .

To keep up with the course, this should be finished by Jan 30.