First, insert sort (insertion sort)
void insertionsort (vector<int > &a) { for (int i=1 ; i<a.size (); ++i) {int tmp=a[i]; int J; for (J=i;j>0 &&tmp< A[j-1 ];--j) {a[j] =a[j-1 ]; // insert tmp in the correct location A[j]=TMP; } }
Ideas:
each time a record to be sorted is inserted in its size into the previously ordered Subsequence (with the fact that the element on the known position 0 to position i-1 is already in an ordered state)
Process:
1) Initially, A[0] into an orderly area, a[1,...., N-1] is a disorderly area, so that I=1
2) Merge A[i] into the current ordered area a[0,..., I-1], forming a new ordered area a[0,...., i]
Select the first a[i of the unordered area] as TMP, compare with the ordered area, move all elements greater than TMP (before position I) to the right, stop when a[j]<tmp is found, insert tmp at A[J+1]
3) I plus 1, repeat 2), until finished a[n-1], sort complete
Complexity of Time:
1) within the cycle, the number of tests for each I value is i+1 times (when the input is reversed), the number of tests in the inner loop is (2+3+...+n) =θ (N2);
2) If the input is ordered (positive order), then the inner loop is not executed, the running time is O (N);
The average run time is O (N2).
Second, the shell sort
Sort algorithm--insert Sort