C Program for Sorting an Array using Shell Sort

By | 15.09.2017

Sorting an Array using Shell Sort


Write a C Program for Sorting an Array using Shell Sort.  Here’s simple C Program for Sorting an Array using Shell Sort in C Programming Language.


Shell Sort


Shell Sort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved.

The idea of Shell Sort is to allow exchange of far items. In Shell Sort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1.

An array is said to be h-sorted if all sub lists of every h’th element is sorted.

Time Complexity: Time complexity of Shell Sort is O(n2).


Also Read : : C Program for Sorting an Array using Insertion Sort

Below is the source code for C Program for Sorting an Array using Shell Sort which is successfully compiled and run on Windows System to produce desired output as shown below :


SOURCE CODE : :


/* C Program for Sorting an Array using Shell Sort */
#include<stdio.h>
#define MAX 100

int main()
{

        int arr[MAX],i,j,k,n,incr;

        printf("\nEnter the number of elements : ");
        scanf("%d",&n);
        for(i=0;i<n;i++)
        {
                printf("\nEnter element %d : ",i+1);
                scanf("%d",&arr[i]);
        }

        printf("\nEnter maximum increment (odd value) : ");
        scanf("%d",&incr);

        /*Shell sort*/
        while(incr>=1)
        {
                for(i=incr; i<n; i++)
                {
                        k=arr[i];
                        for(j=i-incr; j>=0 && k<arr[j]; j=j-incr)
                                arr[j+incr]=arr[j];
                        arr[j+incr]=k;
                }
                incr=incr-2; /*Decrease the increment*/
        }/*End of while*/

        printf("\nSorted list is :\n");
        for(i=0; i<n; i++)
                printf("  %d  ", arr[i]);
        printf("\n");

        return 0;
}/*End of main()*/

OUTPUT : :


/* C Program for Sorting an Array using Shell Sort */

Enter the number of elements : 6

Enter element 1 : 6

Enter element 2 : 1

Enter element 3 : 8

Enter element 4 : 0

Enter element 5 : 7

Enter element 6 : 9

Enter maximum increment (odd value) : 3

Sorted list is :
  0    1    6    7    8    9

Process returned 0

If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.


Thanks for reading the post…


Recommended Posts : :

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments