码迷,mamicode.com
首页 > 编程语言 > 详细

基数排序

时间:2015-04-17 23:40:09      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

(java版)

import java.util.ArrayList;
import java.util.List;

public class radixSort {

public static void sort(int[] a){
//首先确定排序的趟数
int max = a[0];
for(int i=1; i<a.length; i++){
if(a[i] > max){
max = a[i];
}
}
int time = 0;
//判断位数
while(max > 0){
max /= 10;
time++;
}
//建立10个队列
List<ArrayList> queue = new ArrayList<ArrayList>();

for(int i=0; i<10; i++){
ArrayList<Integer> queue1 = new ArrayList<Integer>();
queue.add(queue1);
}
//进行time次分配和收集
for(int i=0; i<time; i++){
//分配数组元素
for(int j=0; j<a.length; j++){
//得到数字的第time+1位数
int x = a[j] % (int)Math.pow(10, i+1)/(int)Math.pow(10, i);
ArrayList<Integer> queue2 = queue.get(x);
queue2.add(a[j]);
queue.set(x,queue2);
}
int count = 0;//元素计数器
//收集队列元素
for(int k=0; k<10; k++){
while(queue.get(k).size() > 0){
ArrayList<Integer> queue3 = queue.get(k);
a[count] = queue3.get(0);
queue3.remove(0);
count++;
}
}
}
}

public static void main(String[] args) {
int[] a = {0,2,5,43,32,65,43,21,87,1};
sort(a);
for(int i =0; i<a.length; i++)
System.out.print(a[i]+" ");
}

}

基数排序

标签:

原文地址:http://www.cnblogs.com/tangtang-123/p/4436048.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!