Insertion sort ( English: Insertion the Sort) is a simple and intuitive sorting algorithm . It works by constructing an ordered sequence , for unsorted data in sorted sequence in the forward and backward scans to find the corresponding position and insert . Insertion sort in the realization, usually sorted in-place (i.e., use only O (1) ordering the extra space), thus forwardly from the scanning process, the need to repeatedly sorted elements gradually move rearward position , the latest element inserted into the space provided.
Generally, insertion sort are implemented using in-place on the array. The algorithm is described as follows:
-
From the first element beginning, the element can be considered has been sorted
-
Remove the next element in the sorted elements in sequence from the forward scan
-
If the element (sorted) is greater than the new element , will the element to the next position
-
Repeat step 3 until it finds the sorted elements less than or equal to the new position of the element
-
The new element is inserted into the discharge position
-
Repeat steps 2 to 5
Insertion sort code is as follows:
. 1 public static void insertSort ( int [] ARR) { 2 for ( int I =. 1; I <arr.length; I ++ ) { . 3 int Key = ARR [I]; . 4 int J = I -. 1 ; . 5 the while (J > = 0 && ARR [J]> Key) { // if the current element is greater than the new element is moved back element . 6 ARR [J +. 1] = ARR [J]; . 7 J, ; . 8 } . 9 ARR [ . 1 + J] = Key; 10 } . 11 }
The algorithm for each element a movement, from the back scan, a forward scan until the last array that the average time complexity is O (N²) , the best case is O (n) (already sorted case), the worst case is O (n²). Algorithm utilizes a temporary variable to exchange elements, the space complexity is O (. 1) .
Test code:
1 public static void main(String[] args) { 2 int[] arr = {1, 1, 2, 0, 9, 3, 12, 7, 8, 3, 4, 65, 22}; 3 4 insertSort(arr); 5 6 for (int i : arr) { 7 System.out.print(i + " "); 8 } 9 }