欢迎光临散文网 会员登陆 & 注册

JAVA,RadixSort,桶排序

2021-07-08 01:06 作者:刘姥姥还喝牛奶  | 我要投稿

public static void sort(List<String> element, int digits) {          //digits-排列位数

   @SuppressWarnings(" unchecked ")
   List<String>[] buckets = (List<String>[]) new ArrayList[128];
   try {
       for (int n = digits - 1; n >= 0; n--) {
           for (String i : element) {
               if (i.length() < digits) {
                   throw new Exception("element" + '"' + i + '"' + " short than digit");
               }
               if (buckets[getBucket(i, n)] == null) {
                   buckets[getBucket(i, n)] = new ArrayList<>();
               }
               buckets[getBucket(i, n)].add(i);
           }
           element.clear();
           for (int i = 0; i < buckets.length; i++) {
               if (buckets[i] != null) {
                   for (int a = 0; a < buckets[i].size(); a++) {
                       element.add(buckets[i].get(a));
                   }
                   buckets[i].clear();
               }
           }

       }
   } catch (Exception e) {
       e.printStackTrace();
   }
}

private static int getBucket(String value, int position) {
   return value.charAt(position);
}

JAVA,RadixSort,桶排序的评论 (共 条)

分享到微博请遵守国家法律