基数排序 ——使用队列的方式排序
每次把存放在数组中的元素拿出时都是按着顺序拿的,先存放的先拿出,所以可以使用队列来实现。
定义10 个队列 0 ——9
和前一个一样 ,按照先个位再十位再百位比较
添加元素和删除元素只需要调用队列的入队和出队方法
//定义一个队列
public class Queue {
//底层使用数组来实现,使用arraylist更加方便,因为arraylist自身有添加和删除的功能
int[] list;
public Queue() {
list = new int[0];
}
//入队
public void add(Integer data){
int[] temp = new int[list.length+1];
for (int i = 0; i < list.length; i++) {
temp[i] = list[i];
}
temp[list.length] = data;
list = temp;
}
//出队
public int remove(){
int value = list[0];
int[] temp = new int[list.length-1];
for (int i = 1; i < list.length; i++) {
temp[i-1] = list[i];
}
this.list = temp;
return value;
}
public boolean isEmpty(){
if(list.length!=0){
return false;
}
return true;
}
}
基数排序Demo:
public class RadixSort2 {
public static void main(String[] args) {
int[] array = new int[]{23,542,15,37,47,27,337,69,86,26};
radixSort(array);
System.out.println(Arrays.toString(array));
}
public static void radixSort(int[] array){
//找到数组中最大的数
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if(array[i]>max){
max = array[i];
}
}
System.out.println("最大的数"+max);
//用于存放临时数据的队列
Queue[] temp = new Queue[10];
//给每个队列初始化一个队列对象
for (int i = 0; i < temp.length; i++) {
temp[i] = new Queue();
}
//计算最大数的位数
int maxLength = (max+"").length();
//进行比较的次数
for (int i = 0,n=1; i < maxLength; i++,n*=10) {
//把每个数字都计算余数
for (int j = 0; j < array.length; j++) {
//计算余数
int remainder = array[j]/n%10;
temp[remainder].add(array[j]);
}
//记录取出数据放的位置
int index = 0;
//把所有的队列都取出
for(int k=0;k<temp.length;k++){
//如果队列不为空
while(!temp[k].isEmpty()){
//取出每组的元素
array[index] = temp[k].remove();
index++;
}
}
}
}
}
490

被折叠的 条评论
为什么被折叠?



