Tuesday 14 February 2017

Implementing shell sort using insertion sort (or) Single program to implement both insertion and shell sort in C

#include<stdio.h>
void Sort(int *a, int n, int gap)
{
    int i, j, temp;
        for(i = gap; i < n; i++)
        {
            for(j = i; j >= gap; j =j-gap)
            {
                 if(a[j]<a[j-gap])
                 {
                          temp = a[j];
                          a[j]=a[j-gap];
                          a[j-gap]=temp; 
}
            }
        }
}

int main()
{
    int i, n, a[10],gap,opt;
    printf("Enter the number of elements :: ");
    scanf("%d",&n);
    printf("Enter the elements :: ");
    for(i = 0; i < n; i++)
         scanf("%d",&a[i]);
    printf("\nPress 1. For Insertion Sort \t 2. Shell Sort \n");
  scanf("%d",&opt);
  switch(opt)
  {
   case 1: Sort(a,n,1);  // For insertion Sort we pass 1 for gap
      break;
  case 2:  for(gap = n/2; gap > 0; gap /= 2)
        {
             Sort(a,n,gap);
        }
}
         
    printf("\nAfter Sorting:: \n ");
    for(i = 0; i < n; i++)
        printf("%d  ",a[i]);
  return 0;
}

Here both insertion and Shell sort use the same function Sort, the only difference between two programs is highlighted in bold

Output: When shell Sort is selected


Output: When Insertion Sort is selected

(OR)
#include<stdio.h>
void Sort(int *a, int n, int increment)
{
    int i, j, tmp;
        for(i = increment; i < n; i++)
        {
            tmp = a[i];
            for(j = i; j >= increment; j -= increment)
            {
                if(tmp < a[j-increment])
                    a[j] = a[j-increment];
                else
                    break;
            }
            a[j] = tmp;
        }
}

int main()
{
    int i, n, a[10],increment,opt;
    printf("Enter the number of elements :: ");
    scanf("%d",&n);
    printf("Enter the elements :: ");
    for(i = 0; i < n; i++)
         scanf("%d",&a[i]);
    printf("\nPress 1. For Insertion Sort \t 2. Shell Sort \n");
scanf("%d",&opt);
switch(opt)
{
case 1: Sort(a,n,1);  // For insertion Sort we pass 1 for increment/gap
break;
case 2:  for(increment = n/2; increment > 0; increment /= 2)
          {
         Sort(a,n,increment);
        // printf("\nafter each increment/gap\n"); for(i = 0; i < n; i++)  printf("%d  ",a[i]);
          }
    
}
         
    printf("\nAfter Sorting:: \n ");
    for(i = 0; i < n; i++)
        printf("%d  ",a[i]);
  return 0;
}

No comments:

Post a Comment