Insert sorting and Hill sorting
Insert sortBy the N-1 sort, the I sort to ensure that the position 0 to the I-1 on the element has been sorted.
This algorithm uses the technique of reducing the number of element exchanges in code implementation: In the for loop, array elements are moved without explicit exchange. The elements on location I are stored in tmp, and all the larger elements before location I are moved to the right, and tmp is placed in the correct position.This technique is the same as the technique used to implement binary heap and heap sorting (which can reduce the number of exchanges and accelerate the speed). For more information, see the C ++ and heap sorting operations such as insertion and deletion of binary heap.
Note:This technique can be used for these operations because they all operate on arrays and use subscript to implement this technique.
The average time of this algorithm is O (N ^ 2 ). Hill's sorting is to break through the barrier of the second time, but ultimately proves that the worst case of time isO (N ^ 2), Hill increment has a great impact on algorithm efficiency.This article only gives a simple idea of hill sorting, and does not involve the selection of hill increment.
/* Insert the C Implementation of sorting. The average condition is O (N ^ 2 ). A total of N-1 round sorting, I round sorting to ensure that the first I (0 to i-1) is in good order */void InsertionSort (int array [], int n) {int I, j; int tmp; for (I = 1; I <n; I ++) {/* here, the array elements are moved without explicit exchange. The elements on location I are stored in tmp, and all the larger elements before location I are moved to the right, and tmp is placed in the correct position. This technique is the same as the technique used to implement a binary heap (which can reduce the number of exchanges and speed up ). */Tmp = array [I]; for (j = I; j> 0 & array [j-1]> tmp; j --) array [j] = array [j-1]; array [j] = tmp ;}} template
Void ShellSort (vector
& Unorder) {// The Hill sorting int gap; int I; for (gap = unorder. size ()/2; gap> 0; gap/= 2) for (I = gap; I <unorder. size (); I ++) {T tmp = unorder [I]; int j = I; for (; j> = gap & tmp <unorder [j-gap]; j-= gap) unorder [j] = unorder [j-gap]; unorder [j] = tmp ;}}