C program to implement Comb sort algorithm

In this tutorial, we will learn how to implement Comb 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 Comb sort algorithm to arrange array elements in ascending order.

C program to implement Comb sort algorithm

The source code to implement the Comb 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 Comb sort algorithm

#include <stdio.h>

#define MAX 5

int newgap(int gap)
{
    gap = (gap * 10) / 13;
    if (gap == 9 || gap == 10)
        gap = 11;

    if (gap < 1)
        gap = 1;

    return gap;
}

void CombSort(int arr[])
{
    int gap = MAX;
    int temp = 0;
    int swapped = 0;

    int i = 0;
    int j = 0;

    while (1) {
        gap = newgap(gap);

        swapped = 0;
        i = 0;
        while (i < MAX - gap) {
            j = i + gap;
            if (arr[i] > arr[j]) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                swapped = 1;
            }
            i++;
        }
        if (gap == 1 && !swapped)
            break;
    }
}

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++;
    }

    CombSort(arr);

    printf("Sorted Array: \n");
    i = 0;
    while (i < MAX) {
        printf("%d ", arr[i]);
        i++;
    }
    printf("\n");

    return 0;
}

Output

RUN 1:
Enter array elements:
Element[0]: 24
Element[1]: 54
Element[2]: 38
Element[3]: 18
Element[4]: 87
Sorted Array: 
18 24 38 54 87

RUN 2:
Enter array elements:
Element[0]: 10
Element[1]: 20
Element[2]: 40
Element[3]: 5
Element[4]: 15
Sorted Array: 
5 10 15 20 40 

Explanation

Here, we created three functions newgap(), CombSort(), and main(). The newgap(), CombSort() functions are responsible to implement Comb sort algorithm.

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




Comments and Discussions!

Load comments ↻






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