用队列来实现基数排序。
在之前的基数排序-JAVA语言实现一文中,采用数组来存储每一个桶中的元素,然后将桶中的元素依次取出进行下一次的排序,由于这种操作方式是先进先出的顺序,满足队列这种数据结构,因此,可以使用对列来作为桶进行数据测存储。
首先创建一个队列类,来实现队列的各种操作,队列的各种操作详情见顺序队列-JAVA语言实现一文。
public class SeqQueue {
private int maxSize; // 表示数组的最大容量
private int front; // 队头
private int rear; // 队尾
private int[] arr; // 该数组用于存放数据, 模拟队列
// 队列的构造器
public SeqQueue(int maxSize) {
front = -1; // 指向队列头部
rear = -1; // 指向队列尾
this.maxSize = maxSize;
arr = new int[maxSize];
}
// 判断队列是否满
public boolean isFull() {
return rear == maxSize - 1;
}
// 判断队列是否为空
public boolean isEmpty() {
return rear == front;
}
// 向队列中添加数据
public void addQueue(int n) {
// 判断队列是否满
if (isFull()) {
System.out.println("队列满,不能加入数据~");
return;
}
rear++; // 让rear 后移
arr[rear] = n;
}
// 获取队列的数据, 出队列
public int getFrontQueue() {
// 判断队列是否空
if (isEmpty()) {
// 通过抛出异常
throw new RuntimeException("队列空,不能取数据");
}
front++; // front后移
return arr[front];
}
// 显示队列的所有数据
public void showQueue() {
if (isEmpty()) {
System.out.println("队列空的,没有数据~~");
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d]=%d\n", i, arr[i]);
}
}
// 显示队列的头数据,不是取出数据
public int headQueue() {
// 判断
if (isEmpty()) {
throw new RuntimeException("队列空的,没有数据~~");
}
return arr[front + 1];
}
}
对基数排序-JAVA语言实现一文中的程序进行改进。 改进后的代码如下所示:
import java.util.Arrays;
public class RadixQueueSort {
public static void main(String[] args) {
int[] arr = new int[]{0,879,78,56,4,15,23,11,47,22,100,468,418};
System.out.println("排序之前:");
System.out.println(Arrays.toString(arr));
radixSort(arr);
System.out.println("排序之后:");
System.out.println(Arrays.toString(arr));
}
public static void radixSort(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();
//创建临时队列数组来存放数字
SeqQueue[] temp = new SeqQueue[10];
//为队列数组赋值
for (int i = 0; i < temp.length; i++){
temp[i] = new SeqQueue(arr.length + 1);
}
//根据最大数据的位数来决定比较次数
for (int i = 0, n = 1; i < maxNumberLength; i++, n *= 10){
//计算每个数字的余数
for (int j = 0; j < arr.length; j++){
//取余数
int moduleNumber = arr[j]/n%10;
//将当前遍历的数字放入指定的队列中
temp[moduleNumber].addQueue(arr[j]);
}
//记录取出的数字所放的位置
int index = 0;
//从队列数组中把数字取出来
for (int k = 0; k < temp.length; k++){
//从队列数组中取出数字
while (!temp[k].isEmpty()){
//取出元素
arr[index] = temp[k].getFrontQueue();
//记录下一个位置
index++;
}
}
}
}
}
对于这种包含两个文件以上的程序时候,为了测试方便,最好放在同一个工程目录下面,方便导入相应的包。