You are on page 1of 4

A brief Presentation on Shell sort

-
Maharshi Rajbhandari
SHELL SORT
• This method separates the original file into sub files.
• The sub-files contain the kth (K is called the increment)element of the original file.
For eg: if the value of k is 5 and a array contains 15 files, the sub files are sorted in the
following manner:
Sub file1: x[0] x[5] x[10]
Sub file 2: x[1] x[6] x[11]
Sub file 3: x[2] x[7] x[12]
Sub file 4: x[3] x[8] x[13] and so on.
• The general formula for the sub file is x[(i-1)*k+j-1].
Working Principle:

• After the files are divided into their respective subfiles, each of the elements of the sub files are sorted by
simple insertion.
• After the first iteration, the value of k is chosen such that it is smaller than the previous value. The sub
files thus created are again sorted.
• The process is repeated until the value of k is 1 so that the subfile consisting of the entire file is sorted.
Example: 26,57,49,38,13,93,87,34 and the sequence of k is (5,2,1)
First iteration: (x[0],x[5]), (x[1],x[6]), (x[2],x[7]), (x[3]), (x[4]).
Second iteration: (x[0].x[3],x[6]), (x[1],x[4],x[7]), (x[2],x[5]).
Third Iteration: (x0,x1,x2,x3,x4,x5,x6,x7.
CODE:
void shellsort(int x[], int n, int incmnt[],int numinc)
Original File: 26 58 49 38 13 93 87 34
{ icr=0
int icr, j, k, span, y;
span=5: 26 58 49 38 13 93 87 34
for(icr =0;icr<numinc ; icr ++)
{
Icr=1
span= incmnt[incr]; // size of increment Span=3: 26 58 34 38 13 93 87 48
for(j= span ; j<n ; j++ )
{icr=2
{
y=x[j];
Span=1: 26 13 34 38 48 93 87 58
for(k= j-span; k>=0 && y<x[k] ;k-=span)
{
x[k+span]=x[k];
x[k+span]=y;
} Sorted file: 13 26 34 38 49 58 87 93
}
}
}

You might also like