/* shellsort: sort v[0]...v[n-1] into increasing order */
void 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;
}
}
int main()
{
int a[]={3,1,2,5,4};
shellsort(a,5);
int i=0;
for (i =0; i < 5; i++)
printf("%d ",a[i]);
return 0;
}
There are three nested loops. The outermost controls the gap between compared elements, shrinking it
from n/2 by a factor of two each pass until it becomes zero. The middle loop steps along the elements.
The innermost loop compares each pair of elements that is separated by gap and reverses any that are
out of order. Since gap is eventually reduced to one, all elements are eventually ordered correctly.
More Info http://en.wikipedia.org/wiki/Shell_sort
1 comment :
Time Complexcity O(nlog^2N)
how ... only innnermost loop run maximum n times both outermoet & outer loop run atmost LogN times & as outer loop run corresponding to outermost loop wihich nothing but (Logn)^2 and thne ineer loop runs corsponding to outer logn^2 time which is O(nlog^2n)
Analysis
http://codepad.org/W7XbE2Eo
Post a Comment