使用低位到高位的顺序,基数为10,使用单向链表接收每一次排后的值,再倒回数组,来回n次(n为最大数值位数)后即排好。写的程序貌似运行很慢,自己也不满意,请大家指点一下~
感觉不如直接用数组倒腾,书上说用10个链表实现,但是不懂怎么做以及为什么要这样做,如何提高效率呢?
package LianXi;
import java.util.Arrays;
import java.util.Random;
//负数对10取余也是负数
class Link5 {
Link5 next;
int data;
public Link5(int i) {
data = i;
}
}
public class BaseNumSort {
static Link5 f;
static int[] a;
static int n;// 最大位数
static void sort() {
int count = 0;
while (count < n) {
count++;
for (int i = 0; i < 10; i++) {// 0~9
for (int j = 0; j < a.length; j++) {
if (count == 1) {
if (a[j] % 10 == i)// 根据个位排列
insert(a[j]);
} else if (count == 2) {
if (a[j] / 10 % 10 == i)// 十位
insert(a[j]);
} else {//其他位
int temp = (int) Math.pow(10, count - 1);
if (a[j] / temp == i)
insert(a[j]);
}
}
}
for (int k = a.length - 1; k >= 0; k--) {
a[k] = remove();
}
}
}
static void insert(int j) {
Link5 newlink = new Link5(j);
if (isEmpty()) {
f = newlink;
} else {
newlink.next = f;
f = newlink;
}
}
static boolean isEmpty() {
return (f == null);
}
static int remove() {
int temp = f.data;
f = f.next;
return temp;
}
public static void main(String[] args) {
n = 2;
int size = 20;
a = new int[size];
Random rand = new Random();
System.out.println("排序前:");
for (int i = 0; i < size; i++) {
int n = rand.nextInt(size * 5);
System.out.print(n + " ");
a[i] = n;
}
System.out.println("\n排序后:");
sort();
System.out.println(Arrays.toString(a));
}
}