Poker is believed that we all have played, the direct insertion sort and playing poker is very similar, grab a poker right hand, and put it into the left hand holding the order of poker inside.
As shown in figure:
Algorithm Introduction:
The direct insertion sort algorithm is the simplest algorithm and the most basic algorithm. So, the insertion sort is to insert the currently-sorted element into a list that is already in order .
The worst time to insert a sort is O (n2), so it is not an optimal sorting algorithm. The feature is simple, does not require extra storage space, and works well when the elements are small.
There are a lot of data types in Java, and the simplest integers are selected, but this is not a general one.
Even if the customized object, the implementation of the java.lang.Comparable, the corresponding greater than (>) and less than (<) for CompareTo can be.
Nonsense not much to say, directly on the code:
/*@ (#) Insertsort.java 2017-4-20
* Copy right 2017 Bank of Communications Co.Ltd.
* All Copyright Reserved * *
package com.sort.cn;
/**
* TODO Document insertsort
* <p>
*
Insert Sort (direct insert sort)
* average O (n^2), preferably O (n), worst O (n^2), Space complexity O (1
@version 1.0.0,2017-4-20
* @author singit *
@since 1.0.0
/public class Insertsort {public
static void Insertionsort (int[] a) {
int tmp;
for (int i = 1; i < A.length. i++) {for
(int j = i; j > 0; j--) {
if (A[j] < a[j-1]) {
TMP = a[ J-1];
A[J-1] = a[j];
A[J] = tmp;
}}} public static void Main (string[] args) {
int[] a = {, B, a, n, all, one, all};
Insertionsort (a);
for (int i:a)
System.out.print (i + "");
}
}
Output results:
Summarize:
Advantages: Stable
Space complexity O (1), Time complexity O (n2)
worst case : reverse order, need to move n (n-1)/2 elements
Best case : Positive sequence, no need to move elements
When an array is sorted or approximate, the best time to insert sort efficiency is O (n), the worst time to insert sort, and the average elapsed time is O (N2).
In general, the insertion Order presents the best performance in the two-time sorting algorithm.
The two-time algorithm works well for lists with fewer elements, such as n<=15. When the list is sorted, the insertion sort is the linear algorithm O (n).
The insertion sort is still a linear algorithm when the list is "approximate sort". An approximate sort condition appears when many elements of a list are already in the correct position.
Some advanced sorting algorithms are implemented by using an O (nlog2n) efficiency algorithm, such as a quick sort, to partially sort the array, and then to select the sort.