Radix Sort Program in Java

In this tutorial, we are going to work on Radix sort program in Java programming language, which is a very time efficient sorting technique.
Radix sort is a non-comparative  integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value. A positional notation is required, but because integers can represent strings of characters and specially formatted floating point numbers, radix sort is not limited to integers.

Radix Sort Program in Java

import java.io.BufferedReader;
import java.io.InputStreamReader;

class RadixSort
{
   static void radixsort(int a[],int d)
   {
     int bmat[][],c[],e=1;
     int i, j, k, m, digit, row, col;

     bmat=new int[a.length][10];

     c= new int[10];

     for(m=1;m<=d;m++)
     {
       for(i=0;i<10;i++)
       {
         c[i]=-1;
       }
       for(i=0;i<a.length;i++)
       {
         digit=(a[i]/e)%10;
         c[digit]++;
         row=c[digit];
         col=digit;
         bmat[row][col]=a[i];
       }
       k=-1;
       for(i=0;i<10;i++)
       {
         if(c[i]!=-1)
         {
           for(j=0;j<=c[i];j++)
           {
             k++;
             a[k]=bmat[j][i];
           }
         }
       }
       e=e*10;
     }
   }
   public static void main (String args[]) throws Exception
   {
     InputStreamReader isr;
     isr = new InputStreamReader(System.in);
     BufferedReader in = new BufferedReader(isr);
     System.out.print("How many values to sort? ");
     int n=Integer.parseInt(in.readLine());

     int a[]=new int[n];
     for(int i=0;i<n;i++)
     {

       System.out.print("Enter value "+ (i+1) +" : ");
       a[i]=Integer.parseInt(in.readLine());
     }

     radixsort(a,3);

     System.out.println("\n" + "Sorted array:");

     for(int i=0;i<n;i++)
     {
       System.out.print(a[i] + " ");
     }
     System.out.println();
   }
}

Output of Radix Sort Program in Java  

As you can see in the above screenshot of Radix Sorting program, firstly we have compiled the java program in CMD through "javac" command and after that we have run the program by "java" command. It ask for the number of elements to be sorted by Radix Sort algorithm, after that this program asks to enter the values of elements and finally displays them in correct sorted order using Radix Sort algorithm technique.

 

2 comments:

Post a Comment