java排序演算法_007基數排序

來源:互聯網
上載者:User
package wzs.sort;// 基數排序// 將所有待比較數值(正整數)統一為同樣的數位長度,數位較短的數前面補零。然後,從最低位開始,依次進行一次排序。// 這樣從最低位排序一直到最高位排序完成以後,數列就變成一個有序序列。import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class radixSort{    public static void main(String[] args)    {        int a[] =        {                49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 101, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51        };        sort(a);        System.out.println("排序後:" + Arrays.toString(a));    }    public static void sort(int[] array)    {        // 首先確定排序的趟數;        int max = array[0];        for (int i = 1; i < array.length; i++)        {            if (array[i] > max)            {                max = array[i];            }        }        int time = 0;        // 判斷位元;        while (max > 0)        {            max /= 10;            time++;        }        // 建立10個隊列;        List<ArrayList> queue = new ArrayList<ArrayList>();        for (int i = 0; i < 10; i++)        {            ArrayList<Integer> queue1 = new ArrayList<Integer>();            queue.add(queue1);        }        // 進行time次分配和收集;        for (int i = 0; i < time; i++)        {            // 分配數組元素;            for (int j = 0; j < array.length; j++)            {                // 得到數位第time+1位元;                int x = array[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);                ArrayList<Integer> queue2 = queue.get(x);                queue2.add(array[j]);                queue.set(x, queue2);            }            int count = 0;// 元素計數器;            // 收集隊列元素;            for (int k = 0; k < 10; k++)            {                while (queue.get(k).size() > 0)                {                    ArrayList<Integer> queue3 = queue.get(k);                    array[count] = queue3.get(0);                    queue3.remove(0);                    count++;                }            }        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.