演算法-java代碼實現基數排序

來源:互聯網
上載者:User

標籤:round   play   value   header   min   tde   attach   edit   答案   

 

基數排序 第11節 基數排序練習題 

對於一個int數組,請編寫一個基數排序演算法,對數組元素排序。

給定一個int數組A及數組的大小n,請返回排序後的數組。保證元素均小於等於2000。

測試範例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
Java (javac 1.7)代碼自動補全     1
import java.util.*;
2
3
 
public class RadixSort {
4
   // 各位裝通法
5
    public int[] radixSort(int[] A, int n) {
6
        int length = n;
7
        int divisor = 1;// 定義每一輪的除數,1,10,100...
8
9
 
        int[][] bucket = new int[10][length];// 定義了10個桶,以防每一位都一樣全部放入一個桶中
10
        int[] count = new int[10];// 統計每個桶中實際存放的元素個數
11
        int digit;// 擷取元素中對應位上的數字,即裝入那個桶
12
13
 
        for (int i = 1; i <= 3; i++) {// 經過4次裝通操作,排序完成
14
            for (int temp : A) {// 計算入桶
15
                digit = (temp / divisor) % 10;
16
                bucket[digit][count[digit]++] = temp;
17
            }
18
19
 
            int k = 0;// 被排序數組的下標
20
            for (int b = 0; b < 10; b++) {// 從0到9號桶按照順序取出
21
                if (count[b] == 0)// 如果這個桶中沒有元素放入,那麼跳過
22
                    continue;
23
                for (int w = 0; w < count[b]; w++) {
24
                    A[k++] = bucket[b][w];
25
                }
26
                count[b] = 0;// 桶中的元素已經全部取出,計數器歸零
27
            }
28
            divisor *= 10;
29
        }
30
        return A;
31
    }
32
}
  您的代碼已儲存
答案正確:恭喜!您提交的程式通過了所有的測試案例

演算法-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.