变长字符串的基数排序

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();
            }
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值