Insert sorting is a simple sorting method, which can be divided into direct insertion sorting and other insertion sorting methods derived from direct insertion sorting.
The basic idea of insert sorting is: in the number of groups to be sorted, suppose n-1 [n> = 2] Number is already sorted, now we need to insert the nth number into the preceding ordered number, so that the N number is in the correct order. This repeats until all the rows are sorted.
The algorithm complexity of this sort method is O (n). Its JAVA Implementation is as follows:
// Insert_sort
Publicint[] Insert_sort (Int[]
ARR ){
Int[] Intarr = arr;
IntI, j, key;
For(J = 1; j <intarr. length; j ++ ){
Key = intarr [J];
I = J-1;
While(I> = 0 & intarr [I]> key ){
Intarr [J] = intarr [I];
I --;
}
Intarr [I + 1] = key;
}
ReturnIntarr;
}
Instance:
Sort the sequence 1, 3, 2, and 5 by inserting a sort order. The sorting process is as follows:
(1) j = 1, key = 3, I = 0 ------- 1 3 2 5
(2) J = 2, key = 2, I = 1--------1 2 3 5
(3) J = 3, key =, I = 2--------1 2 3 5
In the above example, the I auto-subtraction step is omitted. The actual step is to compare intarr [J] with all the elements in front of it every time j increases by 1, when the element before intarr [J] is greater than that before intarr [J], it is exchanged with an element before it until the sorting is complete.