# CMPSCI 311: Theory of Algorithms

### from Wednesday 5 Nov 2003

Here we will use the main idea of Levitin 7.1 to implement a radix sort of strings.


public class StringArray
int n; // length of array
int k; // length of each string
String [] a; // the array of n strings, each must be of length k

public void sortBy (int i)
{// does stable sort on array a by the i'th letter of the strings

public void sort()
{// sorts strings in a lexicographically


• Question 1: Implement the sortBy method, asuming that all the characters in all the strings in the StringArray are ASCII (each character is in the range from 0 through 127 when viewed as a number). Your method should run in O(n) time, treating 128 as a constant. It is all right to make a second array of $n$ strings if you like. Recall that you can cast a character to an int by the operator (int)'' or just by using the character where an int is called for.

• Question 2: Implement the sort method using {\it radix sort} as follows: By applying the different sortBy operations for the various values of i in the right order, and using the fact that sortBy is stable, you can sort the strings completely using O(nk) total time. Give code for this and argue that your code sorts correctly.