When talking about sorting, there will be no less insertion sorting algorithms. It is really classic and simple.
Algorithm: insert sorting
Insertion_sort ()
For j = 2 to A. length
Do key = A [j]
I = J-1
While (I> 0 & A [I]> key)
Do A [I + 1] = A [I]
I = I-1;
A [I + 1] = key
I learned it only after studying the playing cards ..
C ++ code:
// The insertion sorting is obviously O (N ^ 2), but it is better in a certain condition, for example, O (n) is used to sort the order in basic order ), O (nlgn) is used for fast sorting ). In addition, it is ranked in worst_case, and // It is also O (N ^ 2 ). // Code for testing insertsort by Ouyang # include <iostream> using namespace STD; void insertsort (int * a, int Len) {// sort from the second card, by default, the first piece of cards is arranged. // cards are divided into three parts: // 1. arranged, from 1 to J-1 // 2. j // 3. pre-arranged J + 1 to N // If the row in the hand is larger than the pre-arranged I, it will be placed after I // if it is smaller than I, then compare it with the previous one of I until I = 1 // then insert this card to I + 1. For (Int J = 2; j <= Len; j ++) {int key = A [J]; int I = J-1; while (I >=1 & A [I]> key) {A [I + 1] = A [I]; I --;} A [I + 1] = Key ;}} int main () {int array [9] = {null }; int Len = sizeof (array)/sizeof (INT); insertsort (array, Len); For (Int J = 1; j <= Len; j ++) cout <array [J] <"; cout <Endl; return 0 ;}