Add

C program to implement shell sort algorithm



Explanation:

Here, we created two functions shellSort() and main(). The shellSort() function is used to sort array elements in ascending order.

In the main() function, we read array elements from the user. Then we sorted the elements of the array in ascending order using the shellSort() function and print the sorted array on the console screen. 


// C program to implement shell sort algorithm

#include <stdio.h>

#include <stdlib.h>

#define MAX 7

int shellSort(int arr[])

{

    int i = 0;

    int j = 0;

    int k = 0;

    int mid = 0;

    k = MAX / 2;

    while (k > 0) {

        j = k;

        while (j < MAX) {

            i = j - k;

            while (i >= 0) {

                if (arr[i + k] >= arr[i])

                    break;

                else {

                    mid = arr[i];

                    arr[i] = arr[i + k];

                    arr[i + k] = mid;

                }

                i = i - k;

            }

            j++;

        }

        k = k / 2;

    }

    return 0;

}

int main()

{

    int i = 0;

    int arr[MAX];

    printf("Enter array elements:\n");

    while (i < MAX) {

        printf("Element[%d]: ", i);

        scanf("%d", &arr[i]);

        i++;

    }

    shellSort(arr);

    printf("Sorted Array: \n");

    i = 0;

    while (i < MAX) {

        printf("%d ", arr[i]);

        i++;

    }

    printf("\n");

    return 0;

}

Output:

RUN 1:

nter array elements:

Element[0]: 25

Element[1]: 15

Element[2]: 23

Element[3]: 56

Element[4]: 10

Element[5]: 78

Element[6]: 12

Sorted Array:

10 12 15 23 25 56 78

RUN 2:

Enter array elements:

Element[0]: 43

Element[1]: 23

Element[2]: 76

Element[3]: 45

Element[4]: 87

Element[5]: 98

Element[6]: 58

Sorted Array:

23 43 45 58 76 87 98



Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.