Review data structure: Sorting (1) -- insert sorting and data structure sorting
Starting from this article, I began to review the knowledge points of the data structure. The blog mainly focuses on the core idea of each knowledge point and code implementation. This article begins with the insertion sorting in the sorting algorithm.
Stable sorting, inner sorting, suitable for sorting a small amount of data.
When the input array is sorted, the insertion sorting requires O (n) and the fast sorting requires O (n ^ 2 ).
When the input array is sorted in reverse order, the insertion order returns O (n ^ 2 ).
Average time complexity: O (n ^ 2 ).
Insert sorting: Insert a number into an array that has been arranged. by moving the position of this number, the inserted array is also ordered and repeat this process, in this way, all the numbers are ordered.
The implementation code is as follows:
# Include <iostream> using namespace std; void InsertSort (int a [], int n) {for (int I = 1; I <n; I ++) {if (a [I] <a [I-1]) // a [I] is the element to be sorted, with the number of previous I-1 sorted {int j = I-1; // prepare advance int x = a [I]; a [I] = a [I-1]; while (x <a [j]) {a [j + 1] = a [j]; j --;} a [j + 1] = x ;}} int main () {int a [] = {2, 1, 5, 8, 4, 3}; InsertSort (a, 6); for (int I = 0; I <6; I ++) cout <a [I] <''; cout <endl; return 0 ;}