Guest User

Untitled

a guest
Apr 8th, 2016
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1.     @SuppressWarnings("unchecked")
  2.     public static void stringRadixSort(List<String> list, int letters) {
  3.         if (list.size() <= 1) {
  4.             return;
  5.         }
  6.  
  7.         List<String>[] buckets = (List<String>[]) Array.newInstance(List.class, 27);
  8.         for (int i = 0; i < buckets.length; i++) {
  9.             buckets[i] = new LinkedList<>();
  10.         }
  11.         int largestLength = -1;
  12.         int secondLargestLength = 0;
  13.         for (String s : list) {
  14.             int length = s.length();
  15.             if (length >= largestLength) {
  16.                 secondLargestLength = largestLength;
  17.                 largestLength = length;
  18.             } else if (secondLargestLength < length) {
  19.                 secondLargestLength = length;
  20.             }
  21.         }
  22.  
  23.         if (largestLength > letters) {
  24.             throw new IllegalArgumentException("one of the strings is too long");
  25.         }
  26.  
  27.         for (int i = secondLargestLength == largestLength ? secondLargestLength-1 : secondLargestLength; i >= 0; i--) {
  28.             for (String word : list) {
  29.                 int index = (word.length() <= i) ? 0 : word.charAt(i) - ('a' - 1);
  30.                 buckets[index].insertLast(word);
  31.             }
  32.            
  33.             while (!list.isEmpty()) {
  34.                 list.remove(list.first()); //Empties list
  35.             }
  36.  
  37.             for (List<String> bucketList : buckets) {
  38.                 if (bucketList != null) {
  39.                     for (int k = 0; k < bucketList.size(); k++) {               //Iterates through all the buckets
  40.                         list.insertLast(bucketList.remove(bucketList.first())); //Repeatedly removes first element of bucket and adds it to
  41.                     }                                                           //end of the list
  42.                 }
  43.             }
  44.         }
  45.     }
Advertisement
Add Comment
Please, Sign In to add comment