C Program to Sort an Array using Count Sort Technique


 

// Program by Akash Tripathi (@proakash256) 
 
// It is base don keys between a specific range.
// It works by counting the number of objects
// having distinct key values and then doing some
// arithmetic to calculate the position of each
// object in the output Sequence.

#include <stdio.h>
#include <stdlib.h>
void countSort(int *ar , int n)
{
    int max = 0;
    for(int i = 0i < ni = i + 1)
    {
        if(ar[i] > max)
        {
            max = ar[i];
        }
    }
    int range = max 1;
    int *count = (int*)calloc(range , sizeof(int));
    for(int i = 0i < ni = i + 1)
    {
        count[ar[i]] += 1;
    }
    int j = 0;
    int i = 0;
    while (i < range)
    {
        if(count[i] > 0)
        {
            ar[j] = i;
            count[i] -= 1;
            ++j;
        }
        else
            ++i;
    }
    return;
}
int main()
{
    int n;
    printf("Enter the number of elements you
            want to enter in the array : ");
    scanf("%d", &n);
    int ar[n];
    printf("\nEnter the elements :\n");
    for (int i = 0i < ni = i + 1)
        scanf("%d", &ar[i]);
    countSort(ar , n);
    printf("\nThe Sorted array is :\n");
    for (int i = 0i < ni = i + 1)
        printf("%d\n"ar[i]);
    return 0;
}

Comments