Insert sorting divides the array into the left and right sections. The left is sorted, and the elements on the right are not sorted yet.
Start from 1 element on the left side, take an element from the right side, and compare it in the left area. Place it on the left side to a location greater than the element on the right.
Traverse all the elements from the right side and put them to the left side. There are no elements in the rightmost area, that is, the sorting ends.
Public class InsertSort {public void sort (int [] pArray) {if (pArray = null) {throw new NullPointerException ();} int I, j; // traverse the array from left to right. The first on the left is the sorted area by default. // Therefore, the second position begins with I = 1 for (I = 1; I <pArray. length; I ++) {// The array is sorted from left to right, from small to large. // Therefore, if the left side is greater than the right side, shift is required. If (pArray [I-1]> pArray [I]) {int temp = pArray [I]; // sort the range from right to left for (j = I-1; j> = 0 & pArray [j]> temp; j --) {// move all values greater than temp to the right. pArray [j + 1] = pArray [j];} // all left parts are smaller than temp, and all right parts are larger than temp. pArray [j + 1] = temp ;}}}}
Although the first loop starts with I = 1, the input array may have only one element. Calling pArray [1] directly causes the array to cross-border, but the second part of for is used for judgment, therefore, you do not need to perform special processing when the array length is equal to 1.
Note: It is easy to insert the value into the end by mistake. pArray [j + 1] = temp; instead of pArray [j] = temp;
Test the main method:
public static void main(String[] args) {int[] arr = {3, 5, 1, 10, 0, 100, 3, 9};InsertSort insertSortSort = new InsertSort();insertSortSort.sort(arr);for (int i = 0; i < arr.length; i++) {System.out.println("value = "+ arr[i]);}}
Time Complexity: 1 + 2 + 3 +... + (n-1) = n * (n-1)/2 = O (N square)
Best case: O (n)
Worst case: O (n square)
Space complexity: O (1) because no auxiliary space is used
Stability: Stability