Friday, July 20, 2012

Radix Sort Using Java

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 import java.util.*;  
 class radix {  
   //Start counting time.  
   long start = System.nanoTime();  
   public static String[] RadixSort(long[] a) {  
     // convert from long to String  
     String[] s = new String[a.length];  
     for (int i = 0; i < a.length; i++) {  
       s[i] = Long.toString(a[i]);  
     }  
     // get the length of the longest number  
     int l = 0;  
     for (int i = 0; i < s.length; i++) {  
       int current = s[i].length();  
       if (current > l) {  
         l = current;  
       }  
     }  
     // add empty spaces to make the data of equal length  
     String current3 = "";  
     for (int i = 0; i < s.length; i++) {  
       int current2 = s[i].length();  
       for (int j = 1; j <= l-current2; j++) {  
         current3 += " ";  
       }  
       current3 += s[i];  
       s[i] = current3;  
       current3 = "";  
     }  
     // create the buckets  
     String[] tmp1 = new String[s.length];  
     String[] tmp2 = new String[s.length];  
     int tmp1i = 0;  
     int tmp2i = 0;  
     // sort the array  
     for (int i = l; i >= 1; i--) {  
       for (int j = 0; j < s.length; j++) {  
         String current = s[j].substring(i-1, i);  
         if (current.equals(" ") || current.equals("0")) {  
           tmp1[tmp1i] = s[j];  
           tmp1i++;  
         }  
         else {  
           tmp2[tmp2i] = s[j];  
           tmp2i++;  
         }  
       }  
       for (int j = 0; j < tmp1i; j++) {  
         s[j] = tmp1[j];  
       }  
       for (int j = 0; j < tmp2i; j++) {  
         int track = tmp1i;  
         s[track] = tmp2[j];  
         track++;  
       }  
       tmp1i = 0;  
       tmp2i = 0;  
     }  
     return s;  
   }  
   long end = System.nanoTime();  
   //end counting time.  
 }  
 public class radixsort{  
   public static void radixsort() {  
     Scanner scan = new Scanner(System.in);  
     System.out.print("How many values would you like to sort? ");  
     int length = scan.nextInt();  
     long[] a = new long[length];  
     for (int i = 0; i < length; i++) {  
       System.out.print("Enter "+ (i+1)+ " number: ");  
       a[i] = scan.nextLong();  
     }  
     radix r=new radix();  
     r.RadixSort(a);  
     //String[] s = new String[a.length];  
     //s = RadixSort(a);  
     for (int i = 0; i < a.length; i++) {  
       System.out.println(a[i]);  
     }  
     long elapsedTime = r.end - r.start;  
     System.out.println("Running time of heap sort ="+elapsedTime + " nano seconds");  
   }  
 }  

0 comments:

Post a Comment