• 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-002插入排序法(Insertion sort)


    一、介绍

    1.时间和空间复杂度

    运行过程

    2.特点:

    (1)对于已排序或接近排好的数据,速度很快

    (2)对于部分排好序的输入,速度快

    二、代码

      1 package algorithms.elementary21;
      2 
      3 /******************************************************************************
      4  *  Compilation:  javac Insertion.java
      5  *  Execution:    java Insertion < input.txt
      6  *  Dependencies: StdOut.java StdIn.java
      7  *  Data files:   http://algs4.cs.princeton.edu/21sort/tiny.txt
      8  *                http://algs4.cs.princeton.edu/21sort/words3.txt
      9  *  
     10  *  Sorts a sequence of strings from standard input using insertion sort.
     11  *
     12  *  % more tiny.txt
     13  *  S O R T E X A M P L E
     14  *
     15  *  % java Insertion < tiny.txt
     16  *  A E E L M O P R S T X                 [ one string per line ]
     17  *
     18  *  % more words3.txt
     19  *  bed bug dad yes zoo ... all bad yet
     20  *
     21  *  % java Insertion < words3.txt
     22  *  all bad bed bug dad ... yes yet zoo   [ one string per line ]
     23  *
     24  ******************************************************************************/
     25 
     26 import java.util.Comparator;
     27 
     28 import algorithms.util.StdIn;
     29 import algorithms.util.StdOut;
     30 
     31 /**
     32  *  The <tt>Insertion</tt> class provides static methods for sorting an
     33  *  array using insertion sort.
     34  *  <p>
     35  *  This implementation makes ~ 1/2 N^2 compares and exchanges in
     36  *  the worst case, so it is not suitable for sorting large arbitrary arrays.
     37  *  More precisely, the number of exchanges is exactly equal to the number
     38  *  of inversions. So, for example, it sorts a partially-sorted array
     39  *  in linear time.
     40  *  <p>
     41  *  The sorting algorithm is stable and uses O(1) extra memory.
     42  *  <p>
     43  *  See <a href="http://algs4.cs.princeton.edu/21elementary/InsertionPedantic.java.html">InsertionPedantic.java</a>
     44  *  for a version that eliminates the compiler warning.
     45  *  <p>
     46  *  For additional documentation, see <a href="http://algs4.cs.princeton.edu/21elementary">Section 2.1</a> of
     47  *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
     48  *
     49  *  @author Robert Sedgewick
     50  *  @author Kevin Wayne
     51  */
     52 public class Insertion {
     53 
     54     // This class should not be instantiated.
     55     private Insertion() { }
     56 
     57     /**
     58      * Rearranges the array in ascending order, using the natural order.
     59      * @param a the array to be sorted
     60      */
     61     public static void sort(Comparable[] a) {
     62         int N = a.length;
     63         for (int i = 0; i < N; i++) {
     64             for (int j = i; j > 0 && less(a[j], a[j-1]); j--) {
     65                 exch(a, j, j-1);
     66             }
     67             assert isSorted(a, 0, i);
     68         }
     69         assert isSorted(a);
     70     }
     71 
     72     /**
     73      * Rearranges the subarray a[lo..hi] in ascending order, using the natural order.
     74      * @param a the array to be sorted
     75      * @param lo left endpoint
     76      * @param hi right endpoint
     77      */
     78     public static void sort(Comparable[] a, int lo, int hi) {
     79         for (int i = lo; i <= hi; i++) {
     80             for (int j = i; j > lo && less(a[j], a[j-1]); j--) {
     81                 exch(a, j, j-1);
     82             }
     83         }
     84         assert isSorted(a, lo, hi);
     85     }
     86 
     87     /**
     88      * Rearranges the array in ascending order, using a comparator.
     89      * @param a the array
     90      * @param comparator the comparator specifying the order
     91      */
     92     public static void sort(Object[] a, Comparator comparator) {
     93         int N = a.length;
     94         for (int i = 0; i < N; i++) {
     95             for (int j = i; j > 0 && less(a[j], a[j-1], comparator); j--) {
     96                 exch(a, j, j-1);
     97             }
     98             assert isSorted(a, 0, i, comparator);
     99         }
    100         assert isSorted(a, comparator);
    101     }
    102 
    103     /**
    104      * Rearranges the subarray a[lo..hi] in ascending order, using a comparator.
    105      * @param a the array
    106      * @param lo left endpoint
    107      * @param hi right endpoint
    108      * @param comparator the comparator specifying the order
    109      */
    110     public static void sort(Object[] a, int lo, int hi, Comparator comparator) {
    111         for (int i = lo; i <= hi; i++) {
    112             for (int j = i; j > lo && less(a[j], a[j-1], comparator); j--) {
    113                 exch(a, j, j-1);
    114             }
    115         }
    116         assert isSorted(a, lo, hi, comparator);
    117     }
    118 
    119 
    120     // return a permutation that gives the elements in a[] in ascending order
    121     // do not change the original array a[]
    122     /**
    123      * Returns a permutation that gives the elements in the array in ascending order.
    124      * @param a the array
    125      * @return a permutation <tt>p[]</tt> such that <tt>a[p[0]]</tt>, <tt>a[p[1]]</tt>,
    126      *    ..., <tt>a[p[N-1]]</tt> are in ascending order
    127      */
    128     public static int[] indexSort(Comparable[] a) {
    129         int N = a.length;
    130         int[] index = new int[N];
    131         for (int i = 0; i < N; i++)
    132             index[i] = i;
    133 
    134         for (int i = 0; i < N; i++)
    135             for (int j = i; j > 0 && less(a[index[j]], a[index[j-1]]); j--)
    136                 exch(index, j, j-1);
    137 
    138         return index;
    139     }
    140 
    141    /***************************************************************************
    142     *  Helper sorting functions.
    143     ***************************************************************************/
    144     
    145     // is v < w ?
    146     private static boolean less(Comparable v, Comparable w) {
    147         return v.compareTo(w) < 0;
    148     }
    149 
    150     // is v < w ?
    151     private static boolean less(Object v, Object w, Comparator comparator) {
    152         return comparator.compare(v, w) < 0;
    153     }
    154         
    155     // exchange a[i] and a[j]
    156     private static void exch(Object[] a, int i, int j) {
    157         Object swap = a[i];
    158         a[i] = a[j];
    159         a[j] = swap;
    160     }
    161 
    162     // exchange a[i] and a[j]  (for indirect sort)
    163     private static void exch(int[] a, int i, int j) {
    164         int swap = a[i];
    165         a[i] = a[j];
    166         a[j] = swap;
    167     }
    168 
    169    /***************************************************************************
    170     *  Check if array is sorted - useful for debugging.
    171     ***************************************************************************/
    172     private static boolean isSorted(Comparable[] a) {
    173         return isSorted(a, 0, a.length - 1);
    174     }
    175 
    176     // is the array sorted from a[lo] to a[hi]
    177     private static boolean isSorted(Comparable[] a, int lo, int hi) {
    178         for (int i = lo+1; i <= hi; i++)
    179             if (less(a[i], a[i-1])) return false;
    180         return true;
    181     }
    182 
    183     private static boolean isSorted(Object[] a, Comparator comparator) {
    184         return isSorted(a, 0, a.length - 1, comparator);
    185     }
    186 
    187     // is the array sorted from a[lo] to a[hi]
    188     private static boolean isSorted(Object[] a, int lo, int hi, Comparator comparator) {
    189         for (int i = lo + 1; i <= hi; i++)
    190             if (less(a[i], a[i-1], comparator)) return false;
    191         return true;
    192     }
    193 
    194    // print array to standard output
    195     private static void show(Comparable[] a) {
    196         for (int i = 0; i < a.length; i++) {
    197             StdOut.println(a[i]);
    198         }
    199     }
    200 
    201     /**
    202      * Reads in a sequence of strings from standard input; insertion sorts them;
    203      * and prints them to standard output in ascending order.
    204      */
    205     public static void main(String[] args) {
    206         String[] a = StdIn.readAllStrings();
    207         Insertion.sort(a);
    208         show(a);
    209     }
    210 }
  • 相关阅读:
    [Beta阶段]第四次Scrum Meeting
    [Beta阶段]第三次Scrum Meeting
    [Beta阶段]第二次Scrum Meeting
    [Beta阶段]第一次Scrum Meeting
    [Alpha阶段]事后分析博客
    [Alpha阶段]无人转会申请
    Server MyEclipse Tomcat v7.0 was unable to start within 45 seconds. If the server requires more time
    关于单选框、下拉框、复选框的数据回显问题以及全选和全不选
    学习spring和spring mvc过程中遇到的一些问题
    springmvc常用注解之@Controller和@RequestMapping
  • 原文地址:https://www.cnblogs.com/shamgod/p/5420703.html
Copyright © 2020-2023  润新知