排序演算法Java實現(基數排序)

來源:互聯網
上載者:User

標籤:

 1 package sorting; 2  3 /** 4  * 基數排序 5  * 平均O(d(n+r)),最好O(d(n+r)),最壞O(d(n+r));空間複雜度O(n+r);穩定;較複雜 6  * d為位元,r為分配後鏈表的個數 7  * @author zeng 8  * 9  */10 public class JishuPaixu {11 12     public static int getNumInPos(int num, int pos) {13         int tmp = 1;14         for (int i = 0; i < pos - 1; i++) {15             tmp *= 10;16         }17         return (num / tmp) % 10;18     }19 20     public static int getMaxWeishu(int[] b) {21         int max = b[0];22         for (int i = 0; i < b.length; i++) {23             if (b[i] > max)24                 max = b[i];25         }26         int tmp = 1, i = 1;27         while (true) {28             tmp *= 10;29             if (max / tmp != 0) {30                 i++;31             } else32                 break;33         }34         return i;35     }36 37     public static int[] jishupaixu(int[] a, int d) {38 39         int[][] array = new int[10][a.length + 1];40         for (int i = 0; i < 10; i++) {41             array[i][0] = 0;// array[i][0]記錄第i行資料的個數42         }43         for (int pos = 0; pos < d; pos++) {44             System.out.println("start fenpei");45             for (int i = 0; i < a.length; i++) {// 分配過程46                 int num = getNumInPos(a[i], pos + 1);47                 int index = ++array[num][0];48                 System.out.println("a[" + i + "]-->" + "array[" + num + "]["49                         + index + "]");50                 array[num][index] = a[i];51             }52             System.out.println("start shouji");53             for (int i = 0, j = 0; i < 10; i++) {// 收集過程54                 for (int k = 1; k <= array[i][0]; k++) {55                     System.out.println("a[" + j + "]=" + "array[" + i + "]["56                             + k + "]");57                     a[j++] = array[i][k];58                 }59                 array[i][0] = 0;// 複位,下一個pos時還需使用60             }61         }62 63         return a;64     }65 66     public static void main(String[] args) {67         int[] b = { 49, 38, 65, 197, 76, 213, 27, 50 };68         jishupaixu(b, getMaxWeishu(b));69         for (int i : b)70             System.out.print(i + " ");71 72     }73 }

 

排序演算法Java實現(基數排序)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.