home *** CD-ROM | disk | FTP | other *** search
Java Source | 1998-12-14 | 3.0 KB | 111 lines |
- import java.io.*;
-
- /*
- * Sort.class reads a text file specified by args[0] and
- * sorts each line for display
- */
- class Sort {
-
- static final int NMaxLines = 128; // an arbitrary limit
-
- public static void main (String args[]) {
- /*
- * Allocate new array of strings; this is where the file
- * is read and sorted in place
- */
- String sortArray[] = new String [NMaxLines];
- FileInputStream fs=null;
- int nlines;
-
- if (args.length != 1) {
- System.out.println ("usage: java Sort <file>");
- System.exit (1);
- }
- try {
- fs = new FileInputStream (args[0]);
- } catch (Exception e) {
- System.out.println ("Unable to open "+args[0]);
- System.exit (1);
- }
-
- BufferedReader ds = new BufferedReader(new InputStreamReader(fs));
-
- for (nlines=0; nlines<NMaxLines; nlines += 1) {
- try {
- sortArray[nlines] = ds.readLine ();
- if (sortArray[nlines] == null) break;
- } catch (IOException e) {
- System.out.println("Exception caught during read.");
- break;
- }
- }
- try {
- fs.close ();
- } catch (IOException e) {
- System.out.println ("Exception caught closing file.");
- }
-
- /*
- * Sort in place and print
- */
- QSort qsort = new QSort ();
- qsort.sort (sortArray, nlines);
- print (sortArray, nlines);
- }
-
- /*
- * print method prints an array of strings of n elements
- * String a[] array of strings to print
- * int n number of elements
- */
- private static void print (String a[], int n) {
- int i;
-
- for (i=0; i<n; i+=1) System.out.println (a[i]);
- System.out.println ("");
- }
- }
-
- /*
- * QSort.class uses the standard quicksort algorithm
- * Detailed explanation of the techniques are found in online help
- */
- class QSort {
-
- /*
- * This is used internally, so make it private
- */
- private void sort (String a[], int lo0, int hi0) {
- int lo = lo0;
- int hi = hi0;
-
- if (lo >= hi) return;
- String mid = a[(lo + hi) / 2];
- while (lo < hi) {
- while (lo<hi && a[lo].compareTo (mid) < 0) lo += 1;
- while (lo<hi && a[hi].compareTo (mid) > 0) hi -= 1;
- if (lo < hi) {
- String T = a[lo];
- a[lo] = a[hi];
- a[hi] = T;
- }
- }
- if (hi < lo) {
- int T = hi;
- hi = lo;
- lo = T;
- }
- sort(a, lo0, lo); // Yes, it is recursive
- sort(a, lo == lo0 ? lo+1 : lo, hi0);
- }
-
- /*
- * The method called to start the sort
- * String a[] an array of strings to be sorted in place
- * int n the number of elements in the array
- */
- public void sort (String a[], int n) {
- sort (a, 0, n-1);
- }
- }
-