Tuesday, May 3, 2016

Shell Sort

Shell sort works by comparing array elements that are distant rather than adjacent elements.
Shell sort uses an increment sequence. The increment size is reduced after each pass until the increment size is 1. The distance between comparisons decreases as the sorting algorithm runs until the last phase in which adjacent elements are compared hence, it is also known as diminishing increment sort.





#include <stdio.h>

void shell_sort(int arr[], int num)
{
    int i, j, k,swap;
    for (i = num / 2; i > 0; i = i / 2)        /* divide the array to half */
    {
        for (j = i; j < num; j++)             /* j stand in the half of the array  */
        {
            for(k = j - i; k >= 0; k = k - i) /* k stand on the first element in the half made by i */
            {
                if (arr[k+i] >= arr[k])        /* compare elements and swap if else */
                    break;
                else
                {
                    swap = arr[k];
                    arr[k] = arr[k+i];
                    arr[k+i] = swap;
                }
            }
        }
    }
}

int main()
{
    int arr[10];
    int i,  num;
    printf("Enter total number of elements : ");
    scanf("%d", &num);
    printf("\nEnter %d numbers:\n",num);

    for (i =  0 ; i< num; i++)
    {
        scanf("%d", &arr[i]);
    }
    shell_sort(arr, num);
    printf("\nSorted array is: ");
    for (i = 0; i < num; i++){
        printf("%d\t", arr[i]);
    }
    printf("\n");
    return 0;
}










Share this

0 Comment to "Shell Sort"

Post a Comment