w3resource

C Exercises: Display sorted list using Gnome Sort

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

Write a C program to display a sorted list using Gnome sort.

Gnome sort is a sorting algorithm originally proposed by Dr. Hamid Sarbazi-Azad (Professor of Computer Engineering at Sharif University of Technology) in 2000 and called "stupid sort" (not to be confused with bogosort), and then later on described by Dick Grune and named "gnome sort". The algorithm always finds the first place where two adjacent elements are in the wrong order, and swaps them. It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent pair only next to the two swapped elements.

A visualization of the gnome sort:

Python: gnome sort animation

Sample Solution:

Sample C Code:

// https://bit.ly/2rcvXK5
// Gnome Sort Implementation
// Source: https://bit.ly/2rcvXK5
#include <stdio.h>
#include <stdlib.h>
// Function to perform gnome sort on an array
void gnome_sort(int *array, int size) {
    int i, tmp;
    // Iterate through the array
    for (i = 1; i < size; ) {
        // Check if the current element and the previous element are in the correct order
        if (array[i - 1] <= array[i])
            ++i;  // If in order, move to the next element
        else {
            // Swap the current and previous elements
            tmp = array[i];
            array[i] = array[i - 1];
            array[i - 1] = tmp;
            // Move back one position, unless at the beginning of the array
            --i;
            if (i == 0)
                i = 1;
        }
    }
}
// Main function
int main(void) {
    // Input array
    int a[] = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};
    int i;
    size_t n = sizeof(a) / sizeof(a[0]);
    // 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 gnome sort
    gnome_sort(a, n);

    // Display sorted array
    printf("\nSorted Array:\n");
    for (i = 0; i < n; ++i)
        printf("%d ", a[i]);
    return 0;
}

Sample Output:

Original Array:
5 -1 101 -4 0 1 8 6 2 3

Sorted Array:
-4 -1 0 1 2 3 5 6 8 101 

Flowchart:

Flowchart: C Programming - Display sorted list using Gnome Sort

C Programming Code Editor:

Previous: Write a C Program for counting sort.
Next:Write a C program that sort numbers using shell sorting method.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.