基本排序算法——基数排序java实现

基数排序

package basic.sort;

import java.util.Arrays;
import java.util.Random;

public class RadixSort {
    /**
     * use LSD
     * @param number
     * @param d  key code number in fact is the radix;
     */
    private void radixSort(int[] number, int d) {
        int k = 0;
        int n = 1;
        int m = 1;// 控制键值排序依据在哪一位

        int[][] temp = new int[number.length][number.length];
        int[] order = new int[number.length];
        
        while (m <= d) {
            /**
             * distribute
             */
            for (int i = 0; i < number.length; i++) {
                int lsd = ((number[i] / n) % 10);
                temp[lsd][order[lsd]] = number[i];
                order[lsd]++;
            }
            /**
             * collect 
             */
            for (int i = 0; i < d; i++) {
                if (order[i] != 0)
                    for (int j = 0; j < order[i]; j++) {
                        number[k] = temp[i][j];
                        k++;
                    }
                order[i] = 0;
            }
            
            n *= 10;
            k = 0;
            m ++;
        }
    }

    public static void main(String[] args) {
        Random rand = new Random();
        int[] arr = new int[10];
        for(int i = 0 ;i <10 ;i++){
            arr[i] = rand.nextInt(1000);
        }
        println("RadixSort () ");
        
        println(Arrays.toString(arr));    
        new RadixSort().radixSort(arr, 10);        
        println(Arrays.toString(arr));
    }
    
    private static void println(String arg){
        System.out.println(arg);
    }

}

继续学习

posted @ 2013-08-30 12:27  远东悟语  阅读(180)  评论(0编辑  收藏  举报

我是徐冬冬