[Basic idea]
Key: Find the right insertion position in the sequence that is already sorted in front
Steps:
1. Starting with the first element, the element can be considered ordered.
2. Take the next element and compare it in a sequential sequence of elements from a backward-forward scan.
3. If the element (sorted) is greater than the new element, move the element to the next position.
4. Repeat step 3 until you find that the sorted element is less than or equal to the position of the new element.
5. Insert the new element after the position.
6. Repeat steps 2~5
[Java Implementation]
public class insertsort {public static void main (string[] args) {int[] arr = {6, 5, 3, 1, 8, 7, 2, 4}; System.out.println ("Before sorting:"); for (int i = 0; i < arr.length; i++) {System.out.print (Arr[i] + "");} Direct Insert sort insertsort (arr); System.out.println (); System.out.println ("After sorting:"); for (int i = 0; i < arr.length; i++) {System.out.print (Arr[i] + "");}} /** * Direct insertion sort */private static void Insertsort (int[] arr) {int J;//sorted list subscript int t;//To sort elements for (int i = 1; i < Arr.lengt H i++) {if (Arr[i] < arr[i-1]) {t = Arr[i];//Assign value to the element to be sorted for (j = i-1; J >= 0 && arr[j] > t; j--) {Arr[j + 1] = Arr[j]; Iterate through the sorted list, one by one, compared to the element to sort, and if the sorted element is large, move it backward}arr[j + 1] = t; Insert the element to be sorted into the correct position}}}}
Reviews: It is important to set the variable T, which remembers the value of the element to be inserted, and it does not matter when the element is moved.
[Algorithmic features]
Complexity of Time: O (n^2)
Direct insert sorting is better than bubbling and simple sorting performance.
Java sorting Algorithm (iii): Direct Insert Sort