Sort inserted directly into sorting the basic idea
For insertion sort of sorting small number of elements it is very efficient
to be of n ordered elements seen as an unordered and an ordered list table.
Start ordered list contains only one element, unordered list contains n-1 elements,
the sorting process takes out from the first element of the unordered list, it is inserted into the sorted list of suitable position, making new ordered list,
repeated n-1 times to complete the sequencing process may be.
Direct insertion sort Complexity
Preferably: The sequence is ascending order, comparison operations required in this case, the need for the (n-1) times. After the shift assignment 0 times.
I.e., (n) O
time complexity: o (n ^ 2)
direct insertion sort is stable, does not change the relative order of the same elements.
. 1 class InsertionSort {
2
. 3 public void Sort () {
. 4 int [] = {ARR. 1, 32,. 1, 2, 43 is,. 5 ,};
. 5
. 6 IF (ARR == null || arr.length <2 ) {
. 7 return ;
. 8 }
. 9
10 for ( int I =. 1; I <arr.length; I ++ ) {
. 11 // unordered first
12 is int TEMP = ARR [I];
13 is // ordered last
14 int J = I -. 1 ;
15 // When the first element does not reach the array element to be inserted, or the current element is less than
16 the while (J> = 0 && ARR [J]> TEMP) {
. 17 // just after the shift element
18 is ARR [J +. 1] = ARR [J];
. 19 J, ;
20 is }
21 is IF (= J +. 1! I) {
22 is ARR [J +. 1] = TEMP;
23 is }
24 }
25 }
26 is }
Binary insertion sort
to find a new element in the ordered regions in the inserted position, in order to reduce the number of comparison elements to improve efficiency,
using the binary search algorithm to determine the position of insertion.
Binary search worst time complexity: O (log2n)
Therefore, the number of comparisons sorted binary search as: x = log2n
binary search time-consuming operations have insertion sort: comparison and backward assignment. The time complexity of the following:
1) The best case: location lookup is the last bit of a zone behind orderly, without the need for shifting the assignment,
which is the number of comparisons is: log2n. I.e., O (log2n)
2) worst case: the first position is a position looking ordered regions, it is necessary for the number of comparisons: log2n,
the assignment of the number of operations required for n (n-1) / 2 plus ( n-1) times. I.e., O (^ n-2)
. 3) progressive time complexity (average time complexity): O (n ^ 2) the binary search sort is stable, it does not change the relative order of the same elements.