A detailed explanation of the direct insertion sort algorithm and the relevant Java version code implementation _java

Source: Internet
Author: User
Tags array length

Direct Insert Sort

The idea of a direct insertion sort is easy to understand and it is like this:
1. The sorted array is divided into sorted and unsorted parts, and the first element is considered to be in order at the beginning.
2. Starting with the second element, find the appropriate location for the element in the sorted array and insert the location.
3. Repeat the process until the last element is inserted into an ordered array.
4. Sorting completed.

Example:
The idea is simple, but the code isn't as well written as bubble sort. First of all, how to determine the right position? is greater than or equal to left, less than or equal to right? No, many boundary conditions need to be considered, and too many times to judge. Second, inserting elements in an array necessarily requires moving a large number of elements, how to control their movement?
In fact, this is not the problem with the algorithm itself, and how much is related to the programming language. Sometimes the algorithm itself is very mature, to the specific programming language or a little change. Here is the Java algorithm, then take Java to say things.
To solve the above problem, we make a slight refinement of the second step, we do not start from the beginning of the comparison, and from the end of the child array to reverse the comparison, as long as the number of inserts than need to move backwards. Until it is not more than the number, the vacated position is placed in the number that needs to be inserted. So we can write the following code:
Insertarray.java

public class Insertarray {
  //array
  private long[] arr;

  The size of the valid data in the array
  private int elems;

  Default constructor public
  Insertarray () {
    arr = new long[50];
  }

  Public Insertarray (int max) {
    arr = new Long[max];
  }

  Insert data public
  void Insert (Long value) {
    Arr[elems] = value;
    elems++;
  }

  Display data public
  void display () {for
    (int i = 0; i < Elems; i++) {
      System.out.print (Arr[i] + "");
    }
    System.out.println ();
  }

  Insert sort public
  void Insertsort () {
    long select = 0L;
    for (int i = 1; i < Elems i++) {
      select = Arr[i];
      int j = 0;
      for (j = i;j > 0 && arr[j-1] >= Select; j--) {
        arr[j] = arr[j-1];
      }
      ARR[J] = select;}}


Test class:
Testinsertarray.java

public class Testinsertarray {public
  static void Main (string[] args) {
    Insertarray Iarr = new Insertarray ();
    Iarr.insert ();
    Iarr.insert (7856);
    Iarr.insert (a);
    Iarr.insert (8);
    Iarr.insert (5);
    Iarr.insert (a);

    Iarr.display ();
    Iarr.insertsort ();
    Iarr.display ();
  }



Print results:

Algorithm Performance/Complexity
the time complexity of the direct insertion algorithm is now discussed. Regardless of the input, the algorithm will always be n-1 wheel sorting. However, because the insertion point of each element is indeterminate, the input data is greatly affected and its complexity is not certain. We can discuss the best, worst, average three kinds of situations.
1. Best case: It is known from the algorithm, when the array itself is a positive sequence (array ordered and order is the same order as needed, in our discussion premise, that is ascending) is the best, the reason is that in this case, each element needs to be compared once and need not move. The time complexity of the algorithm is O (n);
2. Worst-case scenario: Obviously, when the array to be ranked is in reverse order for the worst case, in which case we compare the number of times per round is i-1, the number of assignments to I. The total number of times is the first n of the series 2n-1, that is, the n^2. The time complexity of the algorithm is O (n^2);
3. Average situation: From the above analysis can be calculated by the average number of algorithms (N^2)/2 (note: This is computed in terms of assignment and comparison, if by moving and comparison, is about N^2/4), obviously, time complexity or O (n^2).
As for the spatial complexity of the algorithm, all movement is carried out within the data, the only cost is that we introduce a temporary variable (some data structure book called "Sentinel"), therefore, its space complexity (extra space) is O (1).

Algorithm stability
because you only need to find a location that is not more than the current number and you do not need to swap, the direct insert sort is a stable sort method.

Algorithm variants
if you want to arrange more data, then every time from the back to find a very large cost, in order to improve the speed of lookup, you can use the binary search (Binary search) for performance optimization. Because of the high efficiency of the binary lookup, it guarantees O (㏒n) complexity, which can greatly improve the search efficiency when the data is more or the input data tends to be the worst. In some books this method is referred to as binary insertion sort. Its code implementation is more complex, there will be time to post it later.
In addition, there are 2-way insert sort and table insertion sort. The 2-way insertion sort is further improved on the basis of binary insertion sequencing, and its moving times are greatly reduced, about N^2/8. However, it does not prevent the number of moves or reduce the level of complexity. Table Insertion Sort completely changes the storage structure, does not move records, but needs to maintain a list of linked list of pointers to modify instead of moving records. Therefore, its complexity is still O (n^2).
For 2-way insert sorting and table insertion sort, you can refer to the book "Data Structure" edited by Min and Wu Weimin.

Algorithm applicable to the scene
the insertion sort is not applicable when the array is large because of the complexity of O (n^2). However, when the data is relatively small, is a good choice, generally as a quick sort of expansion. For example, in the STL sort algorithm and the Stdlib qsort algorithm, the insertion sort is added as a quick sort, and is used for sorting a small number of elements. Also, in the implementation of the sort method used in JDK 7 java.util.Arrays, when the array length is less than 47 o'clock, the insertion sort is used.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.