Ideas:
Each iteration is compared to the previous element, and if it is less than the preceding element, the current element is swapped with the element before it, then the size of the previous element is compared and then the previous element is then exchanged. Terminates the current iteration if it is greater than the previous element. The advantage over selecting a sort is that iterations can be terminated prematurely.
Original array: 5 7 8 2 3 9
Outer Loop once: 5 7 8 2 3 9
Outer Loop two times: 5 7 8 2 3 9
Outer Loop three times: 2 5 7 8 3 9
Outer Loop four times: 2 3 5 7 8 9
Outer Loop five times: 2 3 5 7 8 9
template<classT >voidInsetsort (T data[],intilength) { for(intn=1; n<ilength; n++)//Start comparison from the second element { for(inti = n; I>0; i--) { if(Data[i-1] >Data[i]) {Swap (data[i-1], data[i]); } Else { Break; } } }}
Optimization:
You can see that the following code replaces the above swap (three assignments) with a single assignment.
template< class T >void Insetsort (T data[], int Ilength) { for (int n=1 ; n<ilength; N++ = Data[n]; int I;//save element Temp insertion position. for (i = n; i> 0 && data[i- 1 ] > temp; I--) {Data[i] = Data[i-1
]; } data[i] = temp; }}
Sort the insertion sort algorithm