Second, the shell sort
The shell sort is also called "Reduced incremental Sort" (disminishing increment sort), based on the insertion sort.
The shell suggested sequence is a common but not ideal increment sequence:1,...,n/8,n/4,n/2 (HT=N/2,HK=HK+1/2)
voidShellsort (vector<int> &a) { for(intGap=a.size ()/2;gap>0; gap/=2) {
//For HK (i.e. gap), each position I in hk+1,...,n-1, place the element on position I to i,i-hk,i-2hk ... In the correct position on for(intI=gap;i<a.size (); + +i) {inttmp=A[i]; intj=i; for(; j>=gap&&tmp<a[j-gap];j-=Gap) {A[j]=a[j-Gap]; } A[j]=tmp; } }
Ideas:
By comparing the elements that are separated by a certain interval (HK), the distance used for each comparison decreases with the algorithm until the last order of the adjacent elements is compared.
Steps:
Using an incremental sequence H1,H2,... HT, as long as the h1=1, any increment sequence is feasible.
1) First, the sequence of elements to be ordered into sub-sequences (each sub-sequence consists of an "increment" of elements), respectively, the insertion sort;
After the use of incremental HK a trip to sort, for each I, there is a[i]≤a[i+hk], that is, all elements separated by HK are sorted, at this time, the file is a sort of HK;
A trip to the role of the HK sort, which is to perform an insertion order on the HK independent subarray.
(An important property of the hill sort- a HK-sorted file keeps its HK sort, and will not be broken by the subsequent sequencing.) )
2) Sort by decreasing the increment sequentially and repeating step 1);
3) until HK is 1 o'clock, then a direct insertion of the whole element is sorted (insertion sort);
The pending array is {34,8,64,51,32,21,5} and the array size is n=7, then the increment sequence is 1, 3.
Hk=3, the 3 sub-arrays of {34,51,5},{8,32},{64,21} are inserted in sort (where each array element is 3 apart), hk=3 the sorted array is {5,8,21,34,32,64,51}.
The increment is reduced to hk=1, that is, the entire element is sorted once, and the order is completed, resulting in the final ordered array {5,8,21,32,34,51,64}.
Complexity of Time:
The running time of the shell sort depends on the selection of the increment sequence, which proves to be more complicated.
Using the shell's suggested Delta sequence: 1,...,N/8,N/4,N/2 (HT=N/2,HK=HK+1/2), worst case is θ (N2)
Using the Hibbard increment sequence: 1,3,7,......,2k-1, the worst case is θ (N3/2).
Where applicable:
The normal insertion sort applies to very small amounts of input.
Hill sort is a good choice when the right amount of input, the appropriate increment sequence, excellent performance, and the code is small, easy to write.
Sorting algorithm--shell sorting