java排序演算法_005計數排序

來源:互聯網
上載者:User
package wzs.sort;import java.util.Arrays;//計數排序//找出待排序的數組中最大和最小的元素//統計數組中每個值為i的元素出現的次數,存入數組C的第i項//對所有的計數累加(從C中的第一個元素開始,每一項和前一項相加)//反向填充目標數組:將每個元素i放在新數組的第C(i)項,每放一個元素就將C(i)減去1public class CountingSort{    public static void main(String[] argv)    {        int[] A = CountingSort.countingSort(new int[]        {                10, 3, 5, 7, 9, 1, 4, 2, 6, 8        });        System.out.println(Arrays.toString(A));    }    public static int[] countingSort(int[] A)    {        int[] B = new int[A.length];        // 假設A中的資料a'有,0<=a' && a' < k並且k=100        int k = 100;        countingSort(A, B, k);        return B;    }    private static void countingSort(int[] A, int[] B, int k)    {        int[] C = new int[k];        // 計數        for (int j = 0; j < A.length; j++)        {            int a = A[j];            C[a] += 1;        }        // 求計數和        for (int i = 1; i < k; i++)        {            C[i] = C[i] + C[i - 1];        }        // 整理        for (int j = A.length - 1; j >= 0; j--)        {            int a = A[j];            B[C[a] - 1] = a;            C[a] -= 1;        }    }}

輸出結果:

[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.