java排序演算法_004桶排序

來源:互聯網
上載者:User
package wzs.sort;import java.util.Arrays;//桶排序 (Bucket sort)或所謂的箱排序,是一個排序演算法,工作的原理是將陣列分到有限數量的桶子裡。//每個桶子再個別排序(有可能再使用別的排序演算法或是以遞迴方式繼續使用桶排序進行排序)。桶排序是鴿巢排序的一種歸納結果。//當要被排序的陣列內的數值是均勻分配的時候,桶排序使用線性時間(Θ(n))。但桶排序並不是 比較排序,他不受到 O(n log n) 下限的影響。public class BinSort{    public static void main(String[] args)    {        int intArray[] =        {                10, 3, 5, 7, 9, 1, 4, 2, 6, 8        };        basket(intArray);        System.out.println("排序後:" + Arrays.toString(intArray));    }    public static void basket(int data[]) // data為待排序數組    {        int n = data.length;        int bask[][] = new int[10][n];        int index[] = new int[10];        int max = Integer.MIN_VALUE;        for (int i = 0; i < n; i++)        {            max = max > (Integer.toString(data[i]).length()) ? max : (Integer.toString(data[i]).length());        }        String str;        for (int i = max - 1; i >= 0; i--)        {            for (int j = 0; j < n; j++)            {                str = "";                if (Integer.toString(data[j]).length() < max)                {                    for (int k = 0; k < max - Integer.toString(data[j]).length(); k++)                        str += "0";                }                str += Integer.toString(data[j]);                bask[str.charAt(i) - '0'][index[str.charAt(i) - '0']++] = data[j];            }            int pos = 0;            for (int j = 0; j < 10; j++)            {                for (int k = 0; k < index[j]; k++)                {                    data[pos++] = bask[j][k];                }            }            for (int x = 0; x < 10; x++)                index[x] = 0;        }    }}

輸出結果:

排序後:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

聯繫我們

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