基数排序是一种很特别的排序算法,它不是基于比较进行排序的,而是采用多关键字排序思想,借助“分配”和“收集”两种操作对单逻辑关键字进行排序。
基数排序利用了数字只有0,1,…,9这10个数字的特点, 排序步骤如下:
给定一组数字,如{ 278, 109, 63, 930, 589, 184, 505, 269, 8, 83 }
(1)判断数据在个位数的大小,排列数据;
(2)根据(1)的结果,判断数据十位数的大小,排列数据。如果数据在这个位置的余数相同,那么数据之间的顺序根据上一轮的排列顺序确定;
(3)依次类推,继续判断数据在百位、千位……上面的数据重新排序,直到所有的数据在某一分位上数据全部为0。
public class RadixSort {
public static void main(String[] args) {
int a[] = { 278, 109, 63, 930, 589, 184, 505, 269, 8, 83 };
RadixSort.sort(a);
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public static void sort(int[] array) {
// 首先确定排序的趟数;
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
int time = 0;
// 判断位数;
while (max > 0) {
max /= 10;
time++;
}
// 建立10个队列;
List<ArrayList> queue = new ArrayList<ArrayList>();
for (int i = 0; i < 10; i++) {
ArrayList<Integer> queue1 = new ArrayList<Integer>();
queue.add(queue1);
}
// 进行time次分配和收集;
for (int i = 0; i < time; i++) {
// 分配数组元素;
for (int j = 0; j < array.length; j++) {
// 得到数字的第time+1位数;
int x = array[j] % (int) Math.pow(10, i + 1)
/ (int) Math.pow(10, i);
ArrayList<Integer> queue2 = queue.get(x);
queue2.add(array[j]);
queue.set(x, queue2);
}
int count = 0;// 元素计数器;
// 收集队列元素;
for (int k = 0; k < 10; k++) {
while (queue.get(k).size() > 0) {
ArrayList<Integer> queue3 = queue.get(k);
array[count] = queue3.get(0);
queue3.remove(0);
count++;
}
}
}// for time
}// sort
}
基数排序算法的性能分析:
1)空间效率:一趟排序需要的辅助存储空间为r(r个队列)但以后的排序中重复使用这些队列,所以空间复杂度为O(r)。
2)时间效率:基数排序需要d趟分配和收集,一趟分配需要O(n),一趟收集需要O(r),所以基数排序的时间复杂度为O(d(n+r)),它与序列的初始状态无关。
3)稳定性:对于基数排序算法而言,很重要的一点就是按位排序时必须是稳定的,这也保证了基数排序的稳定性。