Direct insertion and sorting (recursive and non-Recursive Implementation methods)
An array has n elements. If the first n-1 elements have been sorted, insert the n-th element to the first n-1 elements so that the arrays are sorted in an orderly manner.
As for how the n-1 elements have been sorted first, we can assume that the previous N-2 elements have been sorted, insert the n-1 elements to the previous N-2 element.
And so on until only one element is left, that is, the first element. Sorting is completed.
The Code is as follows:
# Include
Using namespace std; void Insert_Sort (int * A, int n) {int I, j, a; for (I = 0; I
Write the recursive version
# Include
Using namespace std; // Insert n into the preceding sorted array void Insert (int * a, int n) {int I = n-1; int key = a [n]; while (I> = 0) & key0) {Insert_Sort (A, n-1); // recursion indicates that Insert (A, n) has been sorted previously );} else // the exit for recursion is n = 0 return;} void main () {int A [4] = {21,2, 34,1}; Insert_Sort (A, 3 ); for (int I = 0; I <4; I ++) {cout <
Time Complexity Analysis:
1. In the best case, the raw data has been sorted, so the time complexity is O (N)
2. In the worst case, the original array is sorted in reverse order, which is O (n2)
3. On average, O (n2)
The closer the element data is to order, the higher the efficiency of direct insertion.