Sunday, April 18, 2010

Radix Sort

import java.util.*;
public class Radix
{                                    
  static void radixsort(int a[], int d)
  {
    int bucket[][] , c[] ,e = 1, i , j , k , m , digit ,row , col;

    //create bucket matrix
    bucket = new int[a.length][10];

    //create c array which stores 10 counters
    c = new int[10];

    for ( m = 1 ; m <= d ; m++)
    {
      //initialize all counters to -1
      for ( i = 0 ; i <= 9 ; i++)
        c[i] = -1;

      //map all array elements into bucket
      for ( i = 0 ; i <= a.length-1 ; i++)
      {
        digit = (a[i] / e) % 10;
        c[digit]++;
        row = c[digit];
        col = digit;
        bucket[row][col] = a[i];
      }

      //copy all buckets back to array a
      k = -1;
      for ( i = 0 ; i <= 9 ; i++)
      {
        if (c[i] != -1)
        {
          for ( j = 0 ; j <= c[i] ; j++)
          {
            k++;
            a[k] = bucket[j][i];
          }
        }
      }

      e = e * 10;
    } // end of for m loop
   } // end of radixsort


public static void main(String args[])
{
  System.out.println("Enter number of elements ");
  Scanner kbd = new Scanner(System.in);

  int n = kbd.nextInt();

  //declare array of n elements

  int a[] = new int[n];
  //scan array from 0 to n-1 locations
  for (int i = 0 ; i <= n-1 ; i++)
  {
    System.out.println("Enter element " + (i+1));
    a[i] = kbd.nextInt();
  }

  //sort the array

  radixsort(a,3); //where 3 are the number of digits


  //print the sorted array
  System.out.println("Sorted array is ");
  for ( int i=0 ; i <= n-1 ; i++)
    System.out.println(a[i]);

} //end of main

} // end of class Radix
/*Output
 Enter number of elements
5
Enter element 1
56
Enter element 2
6
Enter element 3
78
Enter element 4
36
Enter element 5
21
Sorted array is
6
21
36
56
78
*/

0 comments:

Post a Comment

 
ShareThis

Visitor

Website counter
Copyright 2009 Code's. Powered by Blogger
Blogger Templates created by Deluxe Templates
Wordpress by Wpthemescreator
Blogger Showcase