C program to implement shell sort algorithm

In this tutorial, we will how to implement shell sort algorithm using C program? By Nidhi Last updated : August 06, 2023

Problem statement

Here, we will create an array of integers then we will read array elements from the user and implement the Shell sort algorithm to arrange array elements in ascending order.

C program to implement shell sort algorithm

The source code to implement the Shell sort algorithm is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// 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

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.