Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Solution {
- /**
- * Sorts a list of words using MSD radix sort.
- *
- * @param words
- * The list of words to sort.
- * @return The sorted list of words.
- * @throws NullPointerException
- * If `words` equals `null`.
- */
- static List<String> radixSortMSD(List<String> words) {
- return radixSortMSD(words, 0);
- }
- @SuppressWarnings("all")
- static List<String> radixSortMSD(List<String> words, int index){
- //bucketering
- if(index > maxWord(words)) return words;
- List<String>[] buckets = new ArrayList[27];
- buckets[0] = new ArrayList<String>();
- Iterator<String> itr = words.iterator();
- while(itr.hasNext()){
- String word = itr.next();
- if(index == word.length()){
- buckets[0].add(word);
- continue;
- }
- int bucket = Integer.valueOf(word.charAt(index)) - 96;
- if(buckets[bucket] == null) buckets[bucket] = new ArrayList<String>();
- buckets[bucket].add(word);
- }
- for(int k = 0; k < 27; k++){
- if(buckets[k] == null) continue;
- buckets[k] = radixSortMSD(buckets[k], index+1);
- }
- words = unbuckify(buckets);
- return words;
- }
- static ArrayList<String> unbuckify(List<String>[] buckets){
- ArrayList<String> ret = new ArrayList<String>();
- for(int k = 0; k < 27; k++){
- if(buckets[k]==null) continue;
- ret.addAll(buckets[k]);
- }
- return ret;
- }
- static int maxWord(List<String> words){
- int max = 0;
- Iterator<String> itr = words.iterator();
- while(itr.hasNext()){
- String word = itr.next();
- if(word.length() > max) max = word.length();
- }
- return max;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement