插入排序

  1 package edu.princeton.cs.algs4;
  2 /******************************************************************************
  3  *  Compilation:  javac Insertion.java
  4  *  Execution:    java Insertion < input.txt
  5  *  Dependencies: StdOut.java StdIn.java
  6  *  Data files:   http://algs4.cs.princeton.edu/21elementary/tiny.txt
  7  *                http://algs4.cs.princeton.edu/21elementary/words3.txt
  8  *  
  9  *  Sorts a sequence of strings from standard input using insertion sort.
 10  *
 11  *  % more tiny.txt
 12  *  S O R T E X A M P L E
 13  *
 14  *  % java Insertion < tiny.txt
 15  *  A E E L M O P R S T X                 [ one string per line ]
 16  *
 17  *  % more words3.txt
 18  *  bed bug dad yes zoo ... all bad yet
 19  *
 20  *  % java Insertion < words3.txt
 21  *  all bad bed bug dad ... yes yet zoo   [ one string per line ]
 22  *
 23  ******************************************************************************/
 24 
 25 
 26 
 27 import java.util.Comparator;
 28 
 29 /**
 30  *  The {@code Insertion} class provides static methods for sorting an
 31  *  array using insertion sort.
 32  *  <p>
 33  *  This implementation makes ~ 1/2 n^2 compares and exchanges in
 34  *  the worst case, so it is not suitable for sorting large arbitrary arrays.
 35  *  More precisely, the number of exchanges is exactly equal to the number
 36  *  of inversions. So, for example, it sorts a partially-sorted array
 37  *  in linear time.
 38  *  <p>
 39  *  The sorting algorithm is stable and uses O(1) extra memory.
 40  *  <p>
 41  *  See <a href="http://algs4.cs.princeton.edu/21elementary/InsertionPedantic.java.html">InsertionPedantic.java</a>
 42  *  for a version that eliminates the compiler warning.
 43  *  <p>
 44  *  For additional documentation, see <a href="http://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
 45  *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 46  *
 47  *  @author Robert Sedgewick
 48  *  @author Kevin Wayne
 49  */
 50 public class Insertion {
 51 
 52     // This class should not be instantiated.
 53     private Insertion() { }
 54 
 55     /**
 56      * Rearranges the array in ascending order, using the natural order.
 57      * @param a the array to be sorted
 58      */
 59     public static void sort(Comparable[] a) {
 60         int n = a.length;
 61         for (int i = 0; i < n; i++) {
 62             for (int j = i; j > 0 && less(a[j], a[j-1]); j--) {
 63                 exch(a, j, j-1);
 64             }
 65             assert isSorted(a, 0, i);
 66         }
 67         assert isSorted(a);
 68     }
 69 
 70     /**
 71      * Rearranges the subarray a[lo..hi) in ascending order, using the natural order.
 72      * @param a the array to be sorted
 73      * @param lo left endpoint (inclusive)
 74      * @param hi right endpoint (exclusive)
 75      */
 76     public static void sort(Comparable[] a, int lo, int hi) {
 77         for (int i = lo; i < hi; i++) {
 78             for (int j = i; j > lo && less(a[j], a[j-1]); j--) {
 79                 exch(a, j, j-1);
 80             }
 81         }
 82         assert isSorted(a, lo, hi);
 83     }
 84 
 85     /**
 86      * Rearranges the array in ascending order, using a comparator.
 87      * @param a the array
 88      * @param comparator the comparator specifying the order
 89      */
 90     public static void sort(Object[] a, Comparator comparator) {
 91         int n = a.length;
 92         for (int i = 0; i < n; i++) {
 93             for (int j = i; j > 0 && less(a[j], a[j-1], comparator); j--) {
 94                 exch(a, j, j-1);
 95             }
 96             assert isSorted(a, 0, i, comparator);
 97         }
 98         assert isSorted(a, comparator);
 99     }
100 
101     /**
102      * Rearranges the subarray a[lo..hi) in ascending order, using a comparator.
103      * @param a the array
104      * @param lo left endpoint (inclusive)
105      * @param hi right endpoint (exclusive)
106      * @param comparator the comparator specifying the order
107      */
108     public static void sort(Object[] a, int lo, int hi, Comparator comparator) {
109         for (int i = lo; i < hi; i++) {
110             for (int j = i; j > lo && less(a[j], a[j-1], comparator); j--) {
111                 exch(a, j, j-1);
112             }
113         }
114         assert isSorted(a, lo, hi, comparator);
115     }
116 
117 
118     // return a permutation that gives the elements in a[] in ascending order
119     // do not change the original array a[]
120     /**
121      * Returns a permutation that gives the elements in the array in ascending order.
122      * @param a the array
123      * @return a permutation {@code p[]} such that {@code a[p[0]]}, {@code a[p[1]]},
124      *    ..., {@code a[p[n-1]]} are in ascending order
125      */
126     public static int[] indexSort(Comparable[] a) {
127         int n = a.length;
128         int[] index = new int[n];
129         for (int i = 0; i < n; i++)
130             index[i] = i;
131 
132         for (int i = 0; i < n; i++)
133             for (int j = i; j > 0 && less(a[index[j]], a[index[j-1]]); j--)
134                 exch(index, j, j-1);
135 
136         return index;
137     }
138 
139    /***************************************************************************
140     *  Helper sorting functions.
141     ***************************************************************************/
142     
143     // is v < w ?
144     private static boolean less(Comparable v, Comparable w) {
145         return v.compareTo(w) < 0;//若v为a w为b则 v.compareTo(w) < 0为真 因为a为97 b为98
146     }                              //即a[j]=a,a[j-1]=b也就是b在a的前面则考虑互换位置
147 
148     // is v < w ?
149     private static boolean less(Object v, Object w, Comparator comparator) {
150         return comparator.compare(v, w) < 0;
151     }
152         
153     // exchange a[i] and a[j]
154     private static void exch(Object[] a, int i, int j) {
155         Object swap = a[i];
156         a[i] = a[j];
157         a[j] = swap;
158     }
159 
160     // exchange a[i] and a[j]  (for indirect sort)
161     private static void exch(int[] a, int i, int j) {
162         int swap = a[i];
163         a[i] = a[j];
164         a[j] = swap;
165     }
166 
167    /***************************************************************************
168     *  Check if array is sorted - useful for debugging.
169     ***************************************************************************/
170     private static boolean isSorted(Comparable[] a) {
171         return isSorted(a, 0, a.length);
172     }
173 
174     // is the array a[lo..hi) sorted
175     private static boolean isSorted(Comparable[] a, int lo, int hi) {
176         for (int i = lo+1; i < hi; i++)
177             if (less(a[i], a[i-1])) return false;
178         return true;
179     }
180 
181     private static boolean isSorted(Object[] a, Comparator comparator) {
182         return isSorted(a, 0, a.length, comparator);
183     }
184 
185     // is the array a[lo..hi) sorted
186     private static boolean isSorted(Object[] a, int lo, int hi, Comparator comparator) {
187         for (int i = lo+1; i < hi; i++)
188             if (less(a[i], a[i-1], comparator)) return false;
189         return true;
190     }
191 
192    // print array to standard output
193     private static void show(Comparable[] a) {
194         for (int i = 0; i < a.length; i++) {
195             StdOut.println(a[i]);
196         }
197     }
198 
199     /**
200      * Reads in a sequence of strings from standard input; insertion sorts them;
201      * and prints them to standard output in ascending order.
202      *
203      * @param args the command-line arguments
204      */
205     public static void main(String[] args) {
206         String[] a = StdIn.readAllStrings();
207         Insertion.sort(a);
208         show(a);
209     }
210 }
211 
212 /******************************************************************************
213  *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
214  *
215  *  This file is part of algs4.jar, which accompanies the textbook
216  *
217  *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
218  *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
219  *      http://algs4.cs.princeton.edu
220  *
221  *
222  *  algs4.jar is free software: you can redistribute it and/or modify
223  *  it under the terms of the GNU General Public License as published by
224  *  the Free Software Foundation, either version 3 of the License, or
225  *  (at your option) any later version.
226  *
227  *  algs4.jar is distributed in the hope that it will be useful,
228  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
229  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
230  *  GNU General Public License for more details.
231  *
232  *  You should have received a copy of the GNU General Public License
233  *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.
234  ******************************************************************************/

 

posted @ 2017-11-15 09:15  HungryWolfer  阅读(135)  评论(0编辑  收藏  举报