As with selective sorting, the elements on the left side of the current index are sorted, but they are not in the final position, because they need to be moved to make room for smaller data. However, when the index is moved to the far right, the array is fully sorted
//Insertion sort void Insertion(int a[], int l, int r) { int i, j; //The outer circle ensures that the elements before i are in order and their positions are temporarily stable for(i = l+1; i <= r; i++) { //This cycle enables the elements before I to be ordered after the i-th element is added, and the element position is temporarily stable for(j = i; j > l; j--) { if(a[j-1] > a[j]) { swap(a[j-1], a[j]); } } } }
Improvement
The improvement includes: (i) first, put the smallest element in the array in the first place, which can be regarded as the observation post; (ii) in the internal loop, it just makes a simple assignment, and does not perform the exchange operation; (iii) when the element is inserted into the correct position, terminate the internal loop. For each I, insert a[i] into the correct position by moving the element larger than a[i] in a[l],...,a[i-1] to the right, In this way, we can sort a[l],...,a[i]
#include <cstdio> #include <cstdlib> #include <algorithm> #include <stack> #include <queue> #include <malloc.h> using namespace std; #define OK 1 #define ERROR -1 #define TRUE 1 #define FALSE 0 typedef int Status; //Improvement of insertion sorting void Insertion(int a[], int l, int r) { int i, j; //Loop to find the minimum value in the array for(i = r; i > l; i--) { if(a[i-1] > a[i]) { swap(a[i-1], a[i]); } } //Because of the above cycle, a[0]a[1] is in order for(i = l+2; i <= r; i++) { int temp = a[i]; j = i; //At this time, the position of a[j] has been recorded //while loop comparison for shift operation while(temp < a[j-1]) { a[j] = a[j-1]; j--; } //Put the recorded value in the proper position a[j] = temp; } } //Output function void Print(int a[], int l, int r) { int i; for(i = l; i <= r; i++) { printf("%d ", a[i]); } printf("\n"); } int main() { int a[7] = {2, 5, 3, 7, 6, 1, 4}; //Improvement of insertion sorting Insertion(a, 0, 6); Print(a, 0, 6); return 0; }