2012/4/1----基数排序

来源:互联网 发布:出口网络推广 编辑:程序博客网 时间:2024/06/10 03:38

基数排序的核心思想是:把待排序的数组N中的数据分解成为个位,十位,百位.....然后再从个位开始排序,得到第一个数组N1,然后再把N1数组的十位进行排序得到N3,再对N3数组的百位进行排序得到N4,依次这样排序,直到数组中的所有数据的位数都用来排过序了,就可以得到我们所需要的排序数组了。

以下就是过程代码:

Java代码  收藏代码
  1. /* 
  2.  * 基数排序的java实现 
  3.  * @version 1.0 2012/4/1 
  4.  * @author akon 
  5.  */  
  6. package com.akon405.www;  
  7.   
  8. public class RadixSort {  
  9.     public RadixSort(int[] A,int a){  
  10.         int[][] temp=new int[10][A.length];  
  11.         int[] B=new int[10];  
  12.           
  13.         int i,j,k,m;  
  14.         int n=1;  
  15.           
  16.         for(i=1;i<=a;i++){  
  17.             int p=0;  
  18.             //想temp中存数据,数据来自A  
  19.             for(j=0;j<A.length;j++){  
  20.                 k=A[j]/n%10;//A[j]基数位的数值:0--9  
  21.                 temp[k][B[k]]=A[j];//存放在二维数组  中  
  22.                 B[k]++;//起始值为初始化的0,由B[k]的数值可以得到在temp中的第k行存在多少个数值              
  23.             }  
  24.             //从temp中取数据到A  
  25.             for(j=0;j<10;j++){  
  26.                 if(B[j]!=0){//如果二位数组temp所在的列存放的有数据,才对这列进行取数据操作  
  27.                     for(m=0;m<B[j];m++){  
  28.                         A[p]=temp[j][m];//按每次排序之后的顺序存放在A数组中  
  29.                         p++;  
  30.                     }  
  31.                 }  
  32.                 B[j]=0;//供下一次使用,  
  33.             }  
  34.             n=n*10;  
  35.         }  
  36.   
  37.     }  
  38.     /** 
  39.      * @param args 
  40.      */  
  41.     public static void main(String[] args) {  
  42.         // TODO Auto-generated method stub  
  43.         int[] A={21,19,1,8,76};  
  44.         int a=2;//数据的最大位数,这里最大为两位数,所以a为2  
  45.         System.out.print("排序结果:");  
  46.         new RadixSort(A,a);  
  47.         for(int i=0;i<A.length;i++){  
  48.             System.out.print(A[i]+",");  
  49.         }  
  50.     }  
  51.   
  52. }  
 
0 0
原创粉丝点击