Solemnly declare: This article is written by the author based on my personal understanding. errors are inevitable. Please be prepared!
You can reprint, modify, and indicate the source when reprinting!
Algorithm idea:
The method of directly inserting the sort (straight insertion sort) is:
Each time the first element is extracted from the unordered table, it is inserted to the proper position of the ordered table, so that the ordered table is still ordered.
The first step is to compare the first two numbers, and then insert the second number into an ordered table by size. The second step is to scan the third data and the first two numbers from the front to the back, insert the third number to the ordered table by size. perform the following operations in sequence. After (n-1) scanning, the entire sorting process is completed.
Directly inserted sorting is a stable sorting. the time complexity is O (n ^ 2), and the space complexity is O (1 ).
Direct insertion sorting is composed of two nested loops. The outer loop identifies and determines the value to be compared. The inner loop determines its final position for the value to be compared. Direct insertion and sorting compare the value to be compared with the previous value, so the outer loop starts from the second value. When the current value is greater than the value to be compared, continue the loop comparison until a value smaller than the value to be compared is found and the value to be compared is placed in the next position to end the loop.
It is worth noting that we must use a bucket to save the value to be compared, because when the comparison is complete, we need to place the last digit of the value to be smaller than the value to sort the cards like playing cards. The basic way to insert sorting is: each step inserts a record to be sorted into the appropriate position in the previously sorted sequence according to the size of its keyword until all records are inserted.
Initial sequence:
I = 1 [46] 58 15 45 90 18 10 62
Bytes
I = 2 [46 58] 15 45 90 18 10 62
Snapshot -- snapshot
Bytes
I = 3 [15 46 58] 45 90 18 10 62
Snapshot -- snapshot
Bytes
I = 4 [15 45 46 58] 90 18 10 62
Bytes
I = 5 [15 45 46 58 90] 18 10 62
Certificate ----- Certificate
Bytes
I = 6 [15 18 45 46 58 90] 10 62
Certificate -------- Certificate
Bytes
I = 7 [10 15 18 45 46 58 90] 62
Accept-Encoding
Bytes
I = 8 [10 15 18 45 46 58 62 90]
Implementation Code:
1 template <typename T> 2 void sort(T v[], const int sz) 3 { 4 for (int i = 1; i < sz; i++) 5 { 6 T tmp = v[i]; 7 int j = i - 1; 8 while (j >= 0 && v[j] > tmp) 9 {10 v[j+1] = v[j];11 j--;12 }13 v[j+1] = tmp;14 }15 }