PROGRAM FOR RADIXSORT USING C++ Gain Infiniti

PROGRAM FOR RADIXSORT USING C++


#include<iostream>
using namespace std;
static int max_digits;

int pow(int x, int y)
{
     int i,powerValue=1;
    
    if (y==0)
      return 1;

    for (i=1;i<=y;i++)
    powerValue*=x;

      return powerValue;
}


void radixSort(int inputarray[], int n)
{
   int *outputarray, c[10];   //c can have values between 0 and 9
   int j,k,p,digit;
  
   outputarray=new int[n];
   
   //Iterate for the number of Max-Digits in the input array
   for ( p = 0; p < max_digits; p++)
   {
        //Create an array for the digits(0-9)
        for ( k = 0; k < 10; k++)
        c[k] = 0;//Init
       
        //Create A Frequency Array for the digits
        for ( j = 0; j < n; j++)
        {   
            digit = (inputarray[j] % pow(10,p+1) - inputarray[j] % pow (10, p)) / pow(10,p);   //Extract Values of Digits
            c[digit] = c[digit] + 1;    //Calculate Frequency
        }
       
        //Create A Cumulative Frequency Array for the digits
        for ( k = 1; k < 10; k++)
        c[k] = c[k] + c[k-1];
       
        //OutPut Array is formed with stable sort.
        for ( j = n-1; j >= 0; j--)
        {
            digit = (inputarray[j] % pow(10,p+1) - inputarray[j] % pow (10, p)) / pow(10,p);     //Extract Values of Digits
            outputarray[c[digit]] = inputarray[j];
            c[digit] = c[digit]- 1;
        }
       
        for ( j = 1; j <=n; j++)
        inputarray[j] = outputarray[j];        
    }
    delete[] outputarray;
  
}

int main()
{
    int size,*radixSortArray;

    cout<<"Enter the number of Digits in the MaxElement = ";
    cin>>max_digits;
    cout<<"Enter the size of the array = ";
    cin>>size;

    radixSortArray=new int[size];

    for(int i=0;i<size;i++)
    {
        cout <<"Enter the radixSortArray["<<i<<"] = ";
        cin >> radixSortArray[i];
    }

    radixSort(radixSortArray,size);

    cout<<"Array after sorting\n";

    for(int j=1;j<=size;j++)
    cout <<"Enter the radixSortArray["<<j<<"] = "<<radixSortArray[j]<<"\n";

    delete[] radixSortArray;
    return 0;
}
/*
OUTPUT:-

Enter the number of Digits in the MaxElement = 3
Enter the size of the array = 5
Enter the radixSortArray[0] = 555
Enter the radixSortArray[1] = 234
Enter the radixSortArray[2] = 232
Enter the radixSortArray[3] = 323
Enter the radixSortArray[4] = 123
Array after sorting
Enter the radixSortArray[1] = 123
Enter the radixSortArray[2] = 232
Enter the radixSortArray[3] = 234
Enter the radixSortArray[4] = 323
Enter the radixSortArray[5] = 555

*/

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 

Design By Manish and Ranjan