import java.util.ArrayList;
class Solution {
public static void main(String[] args) {
String[] arr = new String[]{"064", "008", "000", "001", "343", "010","0022","2323","0001"};
radixSort(arr, 4);
for (String s : arr)
System.out.print(s + " "); //输出:000 001 008 010 064 343
}
public static void radixSort(String [] arr, int maxLen)
{
final int BUCKETS = 256;
ArrayList<String> [] wordsByLength = new ArrayList[maxLen + 1];
ArrayList<String> [] buckets = new ArrayList[BUCKETS];
for (int i = 0; i < wordsByLength.length; i++)
wordsByLength[i] = new ArrayList<>();
for (int i = 0; i < BUCKETS; i++)
buckets[i] = new ArrayList<>();
for (String s : arr)
wordsByLength[s.length()].add(s);
int idx = 0;
for (ArrayList<String> wordList : wordsByLength)
for (String s : wordList)
arr[idx++] = s;
int startIndex = arr.length;
for (int pos = maxLen - 1; pos >= 0; pos--)
{
startIndex = startIndex - wordsByLength[pos + 1].size();
for (int i = startIndex; i < arr.length; i++)
buckets[arr[i].charAt(pos)].add(arr[i]);
idx = startIndex;
for (ArrayList<String> thisBucket : buckets)
{
for (String s : thisBucket)
arr[idx++] = s;
thisBucket.clear();
}
}
}
}
变长字符串的基数排序
最新推荐文章于 2021-05-17 02:58:04 发布