Simple to understand, insertion sort, it is the original queue constantly out a column value, one by one compared to all the values that have been out of the line, find their position to jump the queue.
The following is the insertion sort to learn own annotations and some code; Further, on the basis of which the interruption code to make a single function.
The following is the code c ++ to insertion sort:
1 #include <iostream> 2 3 using namespace std; 4 5 template<class T> 6 void InsertionSort(T *p, int len); 7 8 int main() 9 { 10 int q[] = {8,5,7,4,0,9,6,2,3,1}; 11 InsertionSort(q, 10); 12 for ( int I = 0 ; I < 10 ; I ++ ) 13 is { 14 COUT << Q [I] << ' ' ; 15 } 16 COUT << endl; . 17 return 0 ; 18 is } . 19 20 is Template < class T> 21 is void InsertionSort (T * P, int len) 22 is { 23 is int line_up, the wait; // line_up column shows the total number of queued 24 // the wait a column index represents the waiting position 25 for (= the wait . 1 ; the wait <len; the wait ++ ) 26 is { 27 T TEM = P [the wait]; 28 line_up = the wait; // last column shows the position of line 29 // initial insertion has been queued in the queue ( there line_up value) 30 the while (line_up> 0 && P [line_up- . 1 ]> = TEM) 31 is { 32 P [line_up] = P [line_up- . 1 ]; // the original values move backward 33 is line_up-- ; // look at the next discharge position Can TEM 34 is } 35 P [line_up] = TEM;// the index position can be selected after interruption of 36 } 37 }
C ++ code that changes
1 #include <iostream> 2 3 using namespace std; 4 5 template<class T> 6 void InsertionSort(T *p, int len); 7 8 template<class T> 9 void Insert(const T& m, T *b, int j); 10 11 int main() 12 { 13 int q[] = {8,5,7,4,0,9,6,2,3,1}; 14 InsertionSort(q, 10); 15 for(int i=0; i<10; i++) 16 { 17 cout << q[i] << ' '; 18 } 19 cout << endl; 20 return 0; 21 } 22 23 template<class T> 24 void InsertionSort(T *p, int len) 25 { 26 int line_up, wait; 27 for(wait=1; wait<len; wait++) 28 { 29 T tem = p[wait]; 30 Insert(tem, p, wait); 31 } 32 } 33 34 template<class T> 35 void Insert(const T& m, T *b, int j) 36 { 37 int i = j; 38 while(i>0 && b[i-1]>=m) 39 { 40 b[i] = b[i-1]; 41 i--; 42 } 43 b[i] = m; 44 }