69,371
社区成员
发帖
与我相关
我的任务
分享
} viod shellsort(int v[], int n)
{
int gap, i, j, temp;
for(gap=n/2; gap>0; gap /=2)
for(i=gap; i<n; ++i)
for(j=i-gap; j>=0&&v[j]>v[j+gap]; j-=gap){
temp=v[j];
v[j]=v[j+gap];
v[j+gap]=temp;
}
}
// Sedgewick's increments give O(n^4/3) upper bound.
// The best known seq: { 1, 5, 19, 41, 109, .... }
// Terms are either 9(4^i) - 9(2^i) + 1, or 4^i - 3(2^i) + 1.
template <class T>
void sedgewick_shell_sort( T a[], int n )
{// UNSTABLE
const static int sedgewick[29] = {
0, 1, 5, 19, 41, 109, 209, 505, 929, 2161, 3905, 8929, 16001, 36289,
64769, 146305, 260609, 587521, 1045505, 2354689, 4188161, 9427969,
16764929, 37730305, 67084289, 150958081, 268386305, 603906049, 1073643521
}; // 0 for end-mark
const int *gap = std::lower_bound( sedgewick, sedgewick+29, n );
if( *gap == n )
++gap;
for( ; *gap > 0; --gap ) {
for( int i = *gap; i < n; ++i ) {
T tmp = a[i];
int j = i;
for( ; j >= *gap && tmp < a[j-*gap]; j -= *gap )
a[j] = a[j-*gap];
a[j] = tmp;
}
}
}