Data Structure Shell Sort

Program of shell sort given below:

//Shell sorting

#include <stdio.h>

void shellsort(int a[], int n) {
    int gap, i, j;
    for (gap = n / 2; gap >= 1; gap = gap / 2) {
        for (j = gap; j < n; j++) {
            for (i = j - gap; i >= 0; i = i - gap) {
                if (a[i + gap] < a[i]) {
                    int temp = a[i + gap];
                    a[i + gap] = a[i];
                    a[i] = temp;
                } else {
                    break;
                }
            }
        }
    }
}

void printArray(int array[], int size) {
    for (int i = 0; i < size; ++i) {
        printf("%d  ", array[i]);
    }
    printf("\n");
}

int main() {
    int n, A[50];
    printf("Enter the size of the array: ");
    scanf("%d", &n);
    printf("Enter the array:\n");
    for (int i = 0; i < n; i++) {
        scanf("%d", &A[i]);
    }
    printf("The unsorted array is:\n");
    printArray(A, n);
    shellsort(A, n);
    printf("The sorted array is:\n");
    printArray(A, n);

    return 0;
}

Output

Enter the size of the array: 7
Enter the array:
09 -7 87 46 51 7 34
The unsorted array is:
9  -7  87  46  51  7  34
The sorted array is:
-7  7  9  34  46  51  87

Leave a Reply

Your email address will not be published. Required fields are marked *

Solverwp- WordPress Theme and Plugin