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(); } }

Here you are doing only three passes, which will give correct results for only a list of integers which are of 3-digits or less. Otherwise it fails. You need to take the number of passes by calculating the maximum number of digits of an element in the list. Then use that as the number of passes.
ReplyDeleteNicely written post. A small suggestion please do add comments in program so that it can be easily understood by the users. It would help you to attract more users for sure and they would find it more useful.
ReplyDeleteSee this : How System.out.println() works in java.