import java.io.*; import java.util.Enumeration; import tree.*; // The TreeSort class uses a binary tree to sort lines in a file and // remove duplicates. Each line is inserted into the tree and the tree // is then enumerated to print each line. The keys for the tree must // implement the TreeKey interface which provides a comparison method // for ordering entries. // How to run the TreeSort Project // JParker, July 23, 1997 // // Create a Java application with 3 source files: TreeSort.java, // Tree.java, and TreeKey.java. The startup class is TreeSort. // Compile and run the application. // // It uses the file name provided on the command line (the // default filename on my point-and-click system is "example1.html" // Your milage may vary) // It enters each -line- of the text file into a sorted binary // tree, and then traverses the tree printing out the lines // in lexecographic order. // Try sorting a large textfile: TreeSort.java will do: longer is better public class TreeSort { public static void main(String[] args) { if (args.length < 1) // Check usage. { System.err.println("Usage: java TreeSort "); return; } try { // Create a DataInputStream so we can read a line at a time. DataInputStream in = new DataInputStream(new FileInputStream(args[0])); // Create a new empty tree. Each line will be added to it. Tree tree = new Tree(); String line; while ((line = in.readLine()) != null) { // Insert the current line into the tree. The StringTreeVal // class implements the TreeVal interface for Strings. tree.insert(new StringKey(line), line); } tree.prettyPrint(); tree.printShape(); tree.inorderPrint(); tree.postorderPrint(); tree.preorderPrint(); System.out.println("\nUse Enumeration to print inorder\n"); // Create an enumeration for the tree that will print its // entries in order. An "inorder" traversal of a tree // prints the left subtree, the current node, then the // right subtree. Enumeration entries = tree.inorder(); while (entries.hasMoreElements()) { System.out.println(entries.nextElement()); } } catch (Exception e) { e.printStackTrace(); return; } } } // The StringKey class contains a String and implements the TreeKey // interface. class StringKey implements TreeKey { // Construct a new StringKey for a given String. StringKey(String val) { stringVal = val; } // Compare the String in this StringKey to the String in // "other" using the "compareTo" method for Strings. public int compare(TreeKey other) { StringKey otherStringKey = (StringKey)other; int compareResult = stringVal.compareTo(otherStringKey.stringVal); if (compareResult < 0) { return TreeKey.LESS; } else if (compareResult == 0) { return TreeKey.EQUAL; } else { return TreeKey.GREATER; } } // Print a StringKey by printing its String. public String toString() { return stringVal; } String stringVal; }