Friday, October 25, 2013

RADIX SORT IN JAVA.

/*
TOPIC: RADIX SORT.
DATE:9/8/2012

*/
import java.util.*;
class RadixSort
{
Scanner sc;
 int x[],n,m;
public RadixSort()
{
sc= new Scanner(System.in);
}
void getData()
{

System.out.println("Enter the number of elements");
n=sc.nextInt();
x= new int[n];
System.out.println("Enter the array");
for(int i=0; i<n; i++)
  x[i]=sc.nextInt();

}
public int findMaxDigit()
{
int max=x[0];
for(int i=1; i<n; i++)
  if(x[i]>max)
      max=x[i];
int d=0;
while(max>0)
{
d++;
max=max/10;
}
return d;
}
public void radixSort()
{
int i,j,d;
d=findMaxDigit();
for(int k=1; k<d; k++)
{
int no[][]= new int[10][20], count[]= new int[10];
System.out.println("K = "+k);
for(i=0; i<n; i++)
{
int dig;
dig=x[i]/(int)(Math.pow(10,k-1))%10;
no[dig][count[dig]++]=x[i];
}
j=0;
for(i=0; i<10; i++)
{
int m=0;
while(m<count[i])
{
x[j++]=no[i][m++];
}
}
display();
}
}

public void display()
{
for( int i=0;i<n; i++)
System.out.print(x[i]+" ");
System.out.println();
}
public static void main(String args[])
{
RadixSort obj =new RadixSort();
obj.getData();
obj.radixSort ();
System.out.println("Sorted Array");
obj.display();
}
}
/*Output
Enter the number of elements
5
Enter the array
1
20
2
30
3
K = 1
20 30 1 2 3
Sorted Array
1 2 3 20 30
*/

No comments:

Post a Comment