C++ insertion sort algorithm

  • 2020-06-19 11:10:01
  • OfStack

This article is an example of C++ sorting algorithm to share the specific code of insertion sort, for your reference, the specific content is as follows

1. Basic idea: Insert the unsorted data elements into the sorted data sequence in order of size. For the unsorted data, scan the sorted sequence from back to front to find the corresponding position and insert it.

For example: insertion sort for 2, 4, 3, 1, 6, 5. Before sorting, the default 2 is ordered and is ordered, while 4, 3, 1, 6 and 5 are unordered and are unordered. Insert the five unordered Numbers into the ordered region in order from small to large.
Sorting in line 1: Compare 4 with 2 in the ordered region. If it is less than 2, insert it in front of 2; if it is greater than 2, insert it after 2. After operation, the ordered area is: {2,4};
Sorting in line 2: compare the number of 3 with each number of the ordered zone (compare the number of the ordered zone from right to left, that is, compare the number of the ordered zone with 4,2 in turn), find the appropriate position to insert, and the ordered zone after operation is: {2,3,4}. I'm going to insert the 3 between the 2 and the 4.
...
Sorting in line 5: the data element 5 is compared with the data in the ordered region, and inserted into the ordered region, and the sorted data sequence is: {1,2,3,4,5,6}.

Conclusion:

1. The first data element in the default unordered region in the first sort is ordered;
2. As can be seen from the above examples, if the number of n is sorted, it needs (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 train number 
 {
 temp = a[i];
 for(j = i; j > 0 && temp < a[j-1]; j--) //  Unordered data is compared to ordered data elements 
 {
  a[j] = a[j-1]; // Moves elements of an 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 in order from small to large, they can be divided into best-case and worst-case discussions.

(1). Best case: The best case is that the data to be sorted has already been sorted, and then only (n-1) comparison operation is needed.
(2). Worst case: The worst case is that the data sequence to be sorted is in reverse order. The number of comparisons required is n(ES34en-1)/2, and the assignment is the number of comparisons n(ES36en-1)/2+(ES37en-1). The average time complexity of the insertion sort algorithm is O(n^2).

Note: Insertion sort is not suitable for sorting applications with large data volumes


Related articles: