The example of this paper shares the specific code of insertion sorting of C + + sorting algorithm for your reference. The specific content is as follows

1. Basic ideas:The unsorted data elements are inserted into the sorted data sequence in order of size. For unsorted data, scan the sorted data sequence from the back to the front, find the corresponding location and insert.

For example: insert 2, 4, 3, 1, 6, 5. Before sorting, by default, 2 is ordered, and 4, 3, 1, 6, 5 are unordered, and they are unordered. Insert these five unordered numbers into the ordered region from the smallest to the largest.
First sorting: compare 4 with 2 of the ordered area. If it is less than 2, insert it in front of 2, and if it is greater than 2, insert it behind 2. The ordered region after operation is: {2,4};
The second sorting: compare 3 with each number of the ordered area (compare with the number of the ordered area from right to left, i.e. compare with 4,2 in turn), find the appropriate location to insert, and the ordered area after operation is: {2,3,4}. Insert 3 between 2 and 4 here.
……
The fifth sorting: compare the data element 5 with the data in the ordered area and insert it into the ordered area. Then the sorted data sequence is: {1,2,3,4,5,6}.

Conclusion:

1. The first data element in the default unordered area is ordered in the first sorting;
2. As can be seen from the above example, if n numbers are sorted, it needs to go through (n-1) times.

2. Code:

``````#include<iostream>

using namespace std;

void insertion_sort(int a[], int len)
{
int i, j, temp;
For (I = 1; I < len; I + +) // control the number of passes
{
temp = a[i];
For (J = I; J > 0 & & Temp < a [J-1]; J --) // compare the data elements in the unordered area with those in the ordered area
{
A [J] = a [J-1]; // move the elements in the ordered region backward
}
a[j] = temp;
}
}

int main()
{
int a[] = {2, 4, 3, 1, 6, 5};

insertion_sort(a, 6);

for (int i = 0; i < 6; i++)
{
cout << a[i] << " ";
}

return 0;
}``````

3. Time complexity analysis:If the data elements to be sorted are sorted from small to large, they can be divided into the best case and the worst case.

(1) . best case: the best case is that the data to be sorted has been sorted. At this time, only (n-1) comparison operations are needed.
(2) Worst case: the worst case is that the data sequence to be sorted is in reverse order. At this time, the number of comparisons to be performed is n (n-1) / 2, and the number of assignments is n (n-1) / 2 + (n-1). On average, the time complexity of insertion sorting algorithm is O (n ^ 2).

Note: insertion sorting is not suitable for sorting applications with large amount of data