Count Sort Algo (C DSA ) 🌟🌟👍👍🎊🎊

 By: Himanshu Tiwari



Counting Sort is a non-comparison-based sorting algorithm that works well when there is limited range of input values. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that information to place the elements in their correct sorted positions.


#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
void printArray(int *A, int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%d ", A[i]);
    }
    printf("\n");
}
int maximum(int arr[],int n){
    int max=INT_MIN;
    for(int i=0; i<n; i++){
        if(max<arr[i]){
            max=arr[i];
        }
    }
    return max;
}
void countsort(int arr[],int n){
    int maxx=maximum(arr,n);
    int * count=(int *)malloc((maxx+1)*sizeof(int ));
    for(int i=0; i<maxx+1; i++){
        count[i]=0;
    }

    for(int i=0; i<n; i++){
        count[arr[i]]=count[arr[i]]+1;
    }

    int i=0;
    int j=0;
    while (i<=maxx)
    {
        if(count[i]>0){
            arr[j]=i;
            count[i]=count[i]-1;
            j++;
        }else{
            i++;
        }
    }
}
int main(){
int arr[]={85,2,47,6,3};
int n=5;
printArray(arr,n);
countsort(arr,n);
printArray(arr,n);

    return 0;
}

Comments

Popular Posts