基數排序的java實現

來源:互聯網
上載者:User
        前幾天師兄問我基數排序怎麼實現,原理我很清楚啊,就給他說了,但是當他詳細問道用具體的計數排序怎樣實現時,我盡然沒有詳細的實現思路。今天有空就把它實現了。不懂理論不行,但是光知道一點理論知識,不去動手實踐是不行的,以後還是要多思,多做。

       詳細代碼如下:

package com.algorithm.sort;import java.util.Arrays;public class RadixSort {//基於計數排序的基數排序演算法private static void radixSort(int[] array,int radix, int distance) {//array為待排序數組//radix,代表基數//代表排序元素的位元int length = array.length;int[] temp = new int[length];//用於暫存元素int[] count = new int[radix];//用於計數排序int divide = 1;for (int i = 0; i < distance; i++) {System.arraycopy(array, 0,temp, 0, length);Arrays.fill(count, 0);for (int j = 0; j < length; j++) {int tempKey = (temp[j]/divide)%radix;count[tempKey]++;}for (int j = 1; j < radix; j++) {count [j] = count[j] + count[j-1];}//個人覺的運用計數排序實現計數排序的重點在下面這個方法for (int j = length - 1; j >= 0; j--) {int tempKey = (temp[j]/divide)%radix;count[tempKey]--;array[count[tempKey]] = temp[j];}divide = divide * radix;}}/** * @param args */public static void main(String[] args) {int[] array = {3,2,3,2,5,333,45566,2345678,78,990,12,432,56};radixSort(array,10,7);for (int i = 0; i < array.length; i++) {System.out.print("  " + array[i]);}}}

聯繫我們

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