zoukankan      html  css  js  c++  java
  • Java实现基数排序

    • 基本介绍

    基数排序属于“分配式排序”,它通过元素的各个位的值,将元素放置对应的“桶”中

    基数排序属于稳定性排序,效率高,但是过多的元素会出现虚拟机运行内存的不足(千万个元素)

    • 基本思想

    把元素统一为同样长度的数组长度   元素较短的数前面补0,比如(1 15 336   看成  001 015 336)

    然后从最低位开始,以此进行排序。

    •  代码实现

    public static void radix_sortin(int[] str) {
      
      // 桶  10个桶  每个桶的最大容量默认为数组长度
      int[][] bucket = new int[10][str.length];
      // 每个桶的当前容量
      int[] capacity = new int[10];
           
      //元素求出最大数                                                                                                                                                                                                                                                                                                                                                                                                                                          
      int max = str[0];
      for (int r = 0; r < str.length; r++) {
       if (str[r] > max) {
        max = str[r];
       }
      }
      //求出最大长度 用于判断循环几大轮 
      int length = (max + "").length();
           
          //取得(个位 十位 百位。。。。)基数     
      for (int b= 0,u=1; b < length; b++,u*=10) {
       for (int i = 0; i < str.length; i++) {
        int base = str[i] /u % 10;  //比如基数为 4
        //将基数按照规则放进桶中
        bucket[base][capacity[base]] = str[i];     //放进第四个桶中 的第一几个当前容量位置
        capacity[base]++;   //容量增加
       }
       
       // 取出数据
       int d = 0;
       for (int k = 0; k < capacity.length; k++) {
        if (capacity[k] != 0) {
         for (int p = 0; p < capacity[k]; p++) {
          str[d] = bucket[k][p];
          d++;
         }
        }
        //注意:清零
        capacity[k] = 0;
       }
      }
     }
  • 相关阅读:
    [CodeForces]Codeforces Round #429 (Div. 2) ABC(待补)
    About Me
    2018-06-14
    Codeforces Codeforces Round #484 (Div. 2) E. Billiard
    Codeforces Codeforces Round #484 (Div. 2) D. Shark
    Codeforces Educational Codeforces Round 44 (Rated for Div. 2) F. Isomorphic Strings
    Codeforces Educational Codeforces Round 44 (Rated for Div. 2) E. Pencils and Boxes
    Codeforces Avito Code Challenge 2018 D. Bookshelves
    Codeforces Round #485 (Div. 2) D. Fair
    Codeforces Round #485 (Div. 2) F. AND Graph
  • 原文地址:https://www.cnblogs.com/miwujun/p/12680876.html
Copyright © 2011-2022 走看看