Two O(n²)-level algorithms, bubble sort and selection sort, were introduced earlier. In this chapter, we will continue to introduce the last O(n²) algorithm, insertion sort.
Basic idea: When we sort the element i, assuming that the elements in front of i are already in order, then we only need to move the element in position i forward, knowing that the element in front of it is less than or equal to it, and the element behind it is greater than it. .
Sort data: 3,5,7,2,4,9,6,8,1
Schematic:
For the first sorting, the element 5 is sorted, and the position greater than 3 remains unchanged.
The second time: sort element 7, compare 7 with 5, 7 is greater than 5, and the position remains unchanged.
Third time: sort element 2, 2 less than 7, swap positions, 2 less than 5 swap positions, 2 less than 3 swap positions.
Fourth time: sort element 4, 4 is less than 7, swap positions, 4 is less than 5, swap positions.
And so on, the fifth sorted array is:
2 3 4 5 7 9 6 8 1
The sixth sorted array is:
2 3 4 5 6 7 9 8 1
The array after the 7th sorting is:
2 3 4 5 6 7 8 9
The array after the 8th sorting is:
1 2 3 4 5 6 7 8 9
It's not hard to write an algorithm based on this demo.
/** * @author:kevin * @Description: Basic sorting * @Date:0:00 2018/3/24 */ public void sort(int[] arr, int n){ for (int i = 1; i < n; i++) { for (int j = i; j >0 ; j--) { if (arr[j] < arr[j-1]){ SortUtil.swap (arr, j, j-1); } } } }
optimization:
Considering the above sorting algorithm, every time we sort element i, if it is smaller than the previous one, we will swap positions. We know that swapping positions is a very time-consuming operation. If we sort element i, we just put Move the element backward until you find the position where the element i should be placed, and then assign the i element to the element that needs to be placed:
/** * @author:kevin * @Description: Optimization 1 * If every time you move forward, you just move the element back, and finally just swap the element to be swapped with it * @Date:0:00 2018/3/24 */ public void sort1(int[] arr, int n){ for (int i = 1; i < n; i++) { int temp = arr[i]; int j = i; for (; j >0 && temp < arr[j-1]; j--) { arr[j] = arr[j-1]; } arr[j] = temp; } }