w3resource

C Exercises: Sort numbers using shell sorting method

C Programming Searching and Sorting Algorithm: Exercise-10 with Solution

Write a C program that sorts numbers using the shell sorting method.

According to Wikipedia "Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange."

Sample Solution:

Sample C Code:

// https://bit.ly/2rcvXK5
// Shell Sort Implementation
// Source: https://bit.ly/2rcvXK5
#include <stdio.h>
// Function to perform shell sort on an array
void shell_sort(int *a, int n) {
    int h, i, j, t;
    // Iterate over different values of h (gap sequence)
    for (h = n; h /= 2;) {
        // Iterate through the array with the current gap h
        for (i = h; i < n; i++) {
            t = a[i];
            // Insertion sort within the subarrays created by the gap
            for (j = i; j >= h && t < a[j - h]; j -= h) {
                a[j] = a[j - h];
            }
            // Place the current element in its correct position
            a[j] = t;
        }
    }
}
// Main function
int main(int ac, char **av) {
    // Input array
    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
    int n = sizeof a / sizeof a[0];
    int i;
    // Display original array
    printf("Original Array:\n");
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    // Sort the array using shell sort
    shell_sort(a, n);
    // Display sorted array
    printf("\nSorted Array:\n");
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    return 0;
}

Sample Output:

Original Array:
4 65 2 -31 0 99 2 83 782 1

Sorted Array:
-31 0 1 2 2 4 65 83 99 782

Flowchart:

Flowchart: C Programming - Sort numbers using shell sorting method

C Programming Code Editor:

Previous: Write a C program to display sorted list using Gnome Sort.
Next: Write a C program that sort numbers using QuickSort method

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/searching-and-sorting/c-search-and-sorting-exercise-11.php