作为一名数据结构初学者,这两天一直在学习排序算法,当我看到基数排序时发现这个排序方法理解起来非常容易(比快速排序和归并排序好多了),但当设计代码时发现这并不简单,在我陷入如何解决获取对应位数的数字时,突然想到了String,将数字转成字符串,通过对字符串的操作来获取对应的结果。这样一来感觉写代码顺多了,以下是我写的代码:
public class RadixSort {
public static void sort(int[] a) {
int[] temp = new int[a.length];
int k = 0;
int level = (int) Math.log10(getArrMax(a)) + 1;//取得此数组中的最大位数
for (int i = 0; i < level; i++) {//共进行的基数排序轮数
for (int j = 0; j <= 9; j++) {//桶子的序号(0~9)
for (int m : a) {//到数组中去寻找对应序号的数放到桶子(temp)里
String s = Integer.toString(m);//将int转换成String类型
if (s.length() <= i) {//表示比当前位数小的,那么它们一定是被放在0号桶
if (j == 0) {//判断是否是0号桶
temp[k++] = m;
}
} else {
int n = s.charAt(s.length() - 1 - i) - '0';//截取当前对应位数的数字
if (n == j) {//判断是否对应桶子的序号
temp[k++] = m;
}
}
}
}
k = 0;//此次基数排序结束,清零以供下一轮使用
System.arraycopy(temp, 0, a, 0, a.length);//将得到的排序写到原数组中
}
}
private static int getArrMax(int[] a) {
int max = 0;
for (int i : a) {
if (i > max) {
max = i;
}
}
return max;
}
public static void main(String[] args) {
int[] a = { 2, 16, 5, 2048, 234, 7, 24, 100, 91, 64, 1024, 32, 9 };
sort(a);
System.out.print("排序后的结果为:");
for (int i : a) {
System.out.print(i + " ");
}
}
}