Copy codeThe Code is as follows: # include <iostream>
Using namespace std;
Void ShellQin (int A [], int n)
{
Int gap = n/2;
Int I, j;
For (; gap> 0; gap = gap/2) // set the initial gap, group by gap, and decrease by gap/2
{
// After the gap is set, insert and sort each element in the corresponding group from the gap to the last element. The gap should be the 2nd elements in the group's location, and the first element is 0.
For (I = gap; I <n; I ++)
{
J = I;
// Insert and sort a group
If (A [j-gap]> A [j])
{
/* If A [j]> A [j-gap] means that A [j] is greater than the previous position in the group
A [j] is saved in temp, and all the numbers greater than A [j] in the group are moved back.
Store A [j]
*/
Int temp = A [j]; // save A [J]
Do
{
A [j] = A [j-gap];
J = j-gap;
} While (j> = 0 & temp <A [j]); // The number of each move greater than A [j]
A [j + gap] = temp; // insert A [j] to A proper position
}
}
}
For (I = 0; I <n; I ++)
{
Cout <* (A + I) <"";
}
}
Int main1 ()
{
Int a [] = {1,100, 4 };
ShellQin (a, 11 );
Return 0;
}
After discussion with friends, although the worst case of hill and plug-in is n square, the reason why Hill's efficiency is better than plug-in is that the coefficient before the time complexity is smaller than the plug-in, especially in reverse order, the number of comparisons is obviously reduced. Just like the fast row to the heap row, the coefficient before the fast row is much smaller than the heap row, and it is easy to use, so it is a favorite of programmers.
The following algorithm is also called shell sorting. the difference with the preceding algorithm is that during insertion sorting, two adjacent data are exchanged instead of the shift (that is, the key keyword is extracted first, shift the value greater than the key backward)Copy codeThe Code is as follows: // exchanges two decimals.
Void swapdouble (double * a, double * B ){
Double temp = *;
* A = * B;
* B = temp;
}
Void Shell (double * p, int n)
{
Int gap = n/2;
Int I, j;
For (; gap> 0; gap = gap/2)
{
For (I = gap; I <= n-1; I ++) // start from the gap and sort the inserts into each group. I = gap is the second element of the group.
{
J = I;
If (* (p + j) <* (p + j-gap ))
{
While (j> = gap & * (p + j) <* (p + j-gap ))
{
Swapdouble (p + j, p + j-gap );
J = j-gap;
}
}
}
}
}