Sunday 4 October 2015

Counting sort / Linear sort

Till now we discussed about sorting which are comparison based and they were taking at-least nlogn time. Here i am discussing a new sorting algorithm that will sort the numbers in linear time but nothing comes free so same case applies here. Counting sort sort the element in linear time but uses lot of your (computer) space  while performing sorting. 

and it creates a array C where it will store the numbers of elements corresponding to indexes and in array B we will be getting the sorted element. 
so here is the program 

#include<stdio.h>
int size;
void main()
{
    int A[]={2,5,4,1,6,5,3,9,6,4,8};
    size=sizeof A/sizeof A[0];
    counting_sort(A);

}
void counting_sort(int *A)
{
    int key = finding_maximum(A);
    int B[size];
    int C[key+1],i;
    for (i=0;i<=key;i++)
    {
        C[i]=0;   /*making all elements of C  zero */
    }
    for(i=0;i<size;i++)
    {

        C[A[i]]=C[A[i]]+1; /*increasing the frequencies of every key(i.e. index of array C)  according to                                            elements in array A*/
    }
    for(i=1;i<=key;i++)
    {
        C[i]=C[i]+C[i-1];   /*adding the frequencies to make it cumulative frequencies in array C */
    }
    for(i=0;i<size;i++)
    {
       B[C[A[i]]-1]=A[i]; /*storing the elements in array B according to the position given in array C */
        C[A[i]]--;
    }
    output(B);
}

int finding_maximum(int *A)
{
    int max =A[0],i;
    for(i=1;i<=size;i++)
    {
        if (A[i]>max)
        {
            max=A[i];
        }
    }
    return max;
}

void output(int *A)
{
    int i;
    for(i=0;i<size;i++)
    {
        printf("%d\n",A[i]);

    }
}

No comments:

Post a Comment