Tuesday, August 28, 2012

C Language program on Shell Sort


This sort technique works by comparing the list elements that are separated by a specific distance i,e a gap until the elements compared within the current gap are in order. Then the gap is reduced and the process continues. When the gap reaches 0 and no interchange is possible then the list is completely sorted.

Suppose a list contains the following elements : 3,44,2,1,5,34,12,22
Size of the above list is 8
gap=Size/2=4

The sorting can be demonstrate to take place as follows
3       44    2    1    5      3     12     22
      3      44    2    1    5      4     12     22
      3      4      2    1    5      44   12     22
      3      4      2    1    5      44   12     22
      3      4      2    1    5      44   12     22
     3       4      2    1    5      44   12     22
     2      4       3    1    5      44    12    22
     2      1       3    4    5      44    12    22
     2      1       3      5      44    12    22
     2      1       3    4        44    12    22
     2      1       3    4    5      44    12    22
     2      1       3    4    5      22    12    44
     2      1       3    4    5      22    12    44
     1      2       3    4    5      22    12    44
     1      2       3    4    5      22    12     44
     1     2        3    4    5      22    12     44
     1     2        3    4    5      22    12     44
     1     2       3     4    5      22    12     44
     1     2       3     4    5      12    22     44
     1     2       3     4    5      12    22     44



#include< stdio.h>
#include< stdlib.h>
void shell(int arr[],int n)
{
 int t,gap,flag,i;
 gap=n/2;
 do
 {
  do
  {
            flag=0;
            for(i=0;i
            {
             if(arr[i]>arr[i+gap])
             {
              t=arr[i];
              arr[i]=arr[i+gap];
              arr[i+gap]=t;
              flag=1;
             }
            }
            }while(flag);
            gap=gap/2;
  }while(gap);
 }
 void main()
 {
  int val[20],i;
  printf("\nUnsorted list is as follows\n");
  randomize();
  for(i=0;i< 20;i++)
  {
            val[i]=rand()%100;
            printf("%4d",val[i]);
  }
  shell(val,20);
             printf("\nSorted list is as follows\n");
  for(i=0;i< 20;i++)
  {
            printf("%4d",val[i]);
  }
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner