基数排序的优化,使用队列实现
参考基数排序的数组实现算法,使用队列实现显得比数组更简洁,快捷。
代码实现:
//自定义的队列
public class MyQueue {
private int maxSize; // 表示数组的最大容量
private int front; // 队头
private int rear; // 队尾
private int[] elements; // 该数组用于存放数据, 模拟队列
// 队列的构造器
public MyQueue(int maxSize) {
front = -1; // 指向队列头部
rear = -1; // 指向队列尾
this.maxSize = maxSize;
elements = new int[maxSize];
}
// 判断队列是否满
public boolean isFull() {
return rear == maxSize - 1;
}
// 判断队列是否为空
public boolean isEmpty() {
return front == rear;
}
// 向队列中添加数据
public void add(int element) {
// 判断队列是否满
if (isFull()) {
System.out.println("队列满,不能加入数据~");
return;
}
rear++; // 让rear 后移
elements[rear] = element;
}
// 获取队列的数据, 出队列
public int poll() {
// 判断队列是否空
if (isEmpty()) {
// 通过抛出异常
throw new RuntimeException("队列空,不能取数据");
}
front++; // front后移
return elements[front];
}
}
//基数排序的优化实现
import java.util.Arrays;
public class RadixQueueSort {
public static void main(String[] args) {
int[] arr = new int[]{1,23,32,45,6,7,189,256,36};
System.out.println("排序之前:");
System.out.println(Arrays.toString(arr));
radixQueueSort(arr);
System.out.println("排序之后:");
System.out.println(Arrays.toString(arr));
}
public static void radixQueueSort(int [] arr){
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++){
if (arr[i] > max){
max = arr[i];
}
}
//计算最大数据的位数
//先将整数转化为字符串,然后调用字符串长度函数
int maxNumberLength = (max + "").length();
//创建临时队列数组来存放数字
MyQueue[] temp = new MyQueue[10];
//为队列数组赋值
for (int i = 0; i < temp.length; i++){
temp[i] = new MyQueue(arr.length+1);
}
//根据最大数据的位数来决定比较次数
for (int i = 0, n = 1; i < maxNumberLength; i++, n *= 10){
//计算每个数字的余数
for (int j = 0; j < arr.length; j++){
//取余数
int ys = arr[j]/n%10;
//将当前遍历的数字放入指定的队列中
temp[ys].add(arr[j]);
}
//记录取出的数字所放的位置
int index = 0;
//从队列数组中把数字取出来
for (int k = 0; k < temp.length; k++){
//从队列数组中取出数字
while (!temp[k].isEmpty()){
//取出元素
arr[index] = temp[k].poll();
//记录下一个位置
index++;
}
}
}
}
}
执行结果: