zoukankan      html  css  js  c++  java
  • 基数排序实现

    基数排序:将待排序数从低位到高位分别排序,从而最后有序

    一个很形象的动画演示:http://www.cs.usfca.edu/~galles/visualization/RadixSort.html

    我的代码及注释:

    package com.sort;
    
    public class RadixSort {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int[] a = {22,64,35,35,35,68,30,88,22,27,41,24};
            radixSort(a, 2);
            System.out.println("the result");
            for(int i = 0 ; i < a.length ; i++ ){
                System.out.print(a[i] + " ");
            }
        }
        
        //第一步先来排序固定位的数字,
        
        public static void radixSort(int[] a, int n){
            int len = a.length;
            int[] temp = new int[len];
            int[] count = new int[10];
            for(int j = 1; j<= n; j++){
                //对count数组进行初始化,清空每一次排序的数据
                for(int i = 0; i < 10; i++ ){
                    count[i] = 0;
                }
                //取相应第j位上的数
                for(int i = 0; i < len; i++){
                    count[(((10*a[i])/(int)(Math.pow(10, j)))%10)]++;
                }
                //输出第各个位的数看看
                for(int i=0;i<10;i++){
                    System.out.print(count[i]+" ");
                }
                System.out.println();
                //得到各个位上的绝对位置,也就是第j趟排序的最终位置
                for(int i = 1; i< 10;i++){
                    count[i] += count[i-1];
                }
                //输出来看看
                for(int i=0;i<10;i++){
                    System.out.print(count[i]+" ");
                }
                System.out.println();
                //收集数据,从原数组收集数据放到相应绝对位置上,从而排序,采用从高位到低位循环,并且每一次都把绝对位置减一
                for(int i = len-1;i>=0;i--){
                    temp[--count[(((10*a[i])/(int)(Math.pow(10, j)))%10)]] = a[i];
                }
                //将temp数组的数付给原数组
                for(int i = 0;i< len ;i++){
                    a[i] = temp[i];
                }
                //第i次排序之后
                System.out.println("the "+j);
                for(int i = 0 ; i < a.length ; i++ ){
                    System.out.print(a[i] + " ");
                }
                System.out.println("
    ");
            }
        }
    
    }

    最后输出的结果:

    1 1 2 0 2 3 0 1 2 0 
    1 2 4 4 6 9 9 10 12 12 
    the 1
    30 41 22 22 64 24 35 35 35 27 68 88 
    
    0 0 4 4 1 0 2 0 1 0 
    0 0 4 8 9 9 11 11 12 12 
    the 2
    22 22 24 27 30 35 35 35 41 64 68 88 
    
    the result
    22 22 24 27 30 35 35 35 41 64 68 88 
  • 相关阅读:
    [HNOI2002]营业额统计
    HDU 1374
    HDU 3345
    HDU 2089
    Graham扫描法
    Codeforces 1144D Deduction Queries 并查集
    Codeforces 916E Jamie and Tree 线段树
    Codeforces 1167F Scalar Queries 树状数组
    Codeforces 1167E Range Deleting
    Codeforces 749E Inversions After Shuffle 树状数组 + 数学期望
  • 原文地址:https://www.cnblogs.com/ironmantony/p/radixsort.html
Copyright © 2011-2022 走看看