Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @SuppressWarnings("unchecked")
- public static void stringRadixSort(List<String> list, int letters) {
- if (list.size() <= 1) {
- return;
- }
- List<String>[] buckets = (List<String>[]) Array.newInstance(List.class, 27);
- for (int i = 0; i < buckets.length; i++) {
- buckets[i] = new LinkedList<>();
- }
- int largestLength = -1;
- int secondLargestLength = 0;
- for (String s : list) {
- int length = s.length();
- if (length >= largestLength) {
- secondLargestLength = largestLength;
- largestLength = length;
- } else if (secondLargestLength < length) {
- secondLargestLength = length;
- }
- }
- if (largestLength > letters) {
- throw new IllegalArgumentException("one of the strings is too long");
- }
- for (int i = secondLargestLength == largestLength ? secondLargestLength-1 : secondLargestLength; i >= 0; i--) {
- for (String word : list) {
- int index = (word.length() <= i) ? 0 : word.charAt(i) - ('a' - 1);
- buckets[index].insertLast(word);
- }
- while (!list.isEmpty()) {
- list.remove(list.first()); //Empties list
- }
- for (List<String> bucketList : buckets) {
- if (bucketList != null) {
- for (int k = 0; k < bucketList.size(); k++) { //Iterates through all the buckets
- list.insertLast(bucketList.remove(bucketList.first())); //Repeatedly removes first element of bucket and adds it to
- } //end of the list
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment