1 /****************************************************************************** 2 * Compilation: javac Shell.java 3 * Execution: java Shell < input.txt 4 * Dependencies: StdOut.java StdIn.java 5 * Data files: http://algs4.cs.princeton.edu/21elementary/tiny.txt 6 * http://algs4.cs.princeton.edu/21elementary/words3.txt 7 * 8 * Sorts a sequence of strings from standard input using shellsort. 9 * 10 * Uses increment sequence proposed by Sedgewick and Incerpi. 11 * The nth element of the sequence is the smallest integer >= 2.5^n 12 * that is relatively prime to all previous terms in the sequence. 13 * For example, incs[4] is 41 because 2.5^4 = 39.0625 and 41 is 14 * the next integer that is relatively prime to 3, 7, and 16. 15 * 16 * % more tiny.txt 17 * S O R T E X A M P L E 18 * 19 * % java Shell < tiny.txt 20 * A E E L M O P R S T X [ one string per line ] 21 * 22 * % more words3.txt 23 * bed bug dad yes zoo ... all bad yet 24 * 25 * % java Shell < words3.txt 26 * all bad bed bug dad ... yes yet zoo [ one string per line ] 27 * 28 * 29 ******************************************************************************/ 30 31 package edu.princeton.cs.algs4; 32 33 /** 34 * The {@code Shell} class provides static methods for sorting an 35 * array using Shellsort with Knuth's increment sequence (1, 4, 13, 40, ...). 36 * <p> 37 * For additional documentation, see <a href="http://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of 38 * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. 39 * 40 * @author Robert Sedgewick 41 * @author Kevin Wayne 42 */ 43 public class Shell { 44 45 46 private Shell() { } 47 48 52 public static void sort(Comparable[] a) { 53 int n = a.length; 54 55 56 int h = 1; 57 while (h < n/3) h = 3*h + 1; 58 59 while (h >= 1) { 60 61 for (int i = h; i < n; i++) { 62 for (int j = i; j >= h && less(a[j], a[j-h]); j -= h) { 63 exch(a, j, j-h); 64 } 65 } 66 assert isHsorted(a, h); 67 h /= 3; 68 } 69 assert isSorted(a); 70 } 71 72 73 77 78 79 private static boolean less(Comparable v, Comparable w) { 80 return v.compareTo(w) < 0; 81 } 82 83 84 private static void exch(Object[] a, int i, int j) { 85 Object swap = a[i]; 86 a[i] = a[j]; 87 a[j] = swap; 88 } 89 90 91 94 private static boolean isSorted(Comparable[] a) { 95 for (int i = 1; i < a.length; i++) 96 if (less(a[i], a[i-1])) return false; 97 return true; 98 } 99 100 101 private static boolean isHsorted(Comparable[] a, int h) { 102 for (int i = h; i < a.length; i++) 103 if (less(a[i], a[i-h])) return false; 104 return true; 105 } 106 107 108 private static void show(Comparable[] a) { 109 for (int i = 0; i < a.length; i++) { 110 StdOut.println(a[i]); 111 } 112 } 113 114 120 public static void main(String[] args) { 121 String[] a = StdIn.readAllStrings(); 122 Shell.sort(a); 123 show(a); 124 } 125 126 } 127