counting sort

 #include<iostream>

using namespace std;
void counting_sort(int arr[],int n,int max)
{
    int i;
    //create the count array
    int count[max+1];
    for ( i = 0; i <= max; i++)
    {
        count[i]=0;
    }
    //store the count of each element
    for ( i = 0; i < n ; i++)
    {
        count[arr[i]]++;
    }
    //cummulative frequency
    for ( i = 1; i <= max; i++)
    {
        count[i]+=count[i-1];
    }
    //create a output array to store the sorted numbers
    int output[n];
    for ( i = n-1; i>=0; i--)
    {
        output[count[arr[i]]-1]=arr[i];
        count[arr[i]]--;
    }
    //copy output array to original array
    for ( i = 0; i < n; i++)
    {
        arr[i]=output[i];
    }
}
int main()
{
    int arr[10],n,max,i;
    cout<<"Enter the number of elements: ";
    cin>>n;
    cout<<"Enter the array elements: ";
    for ( i = 0; i < n; i++)
    {
        cin>>arr[i];
    }
    //find the maximum element
    max=arr[0];
    for ( i = 1; i < n; i++)
    {
        if (max<arr[i])
        {
            max=arr[i];
        }  
    }
    counting_sort(arr,n,max);
    //print the original array
    for ( i = 0; i < n; i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

Comments

Popular Posts