基数排序

来源:互联网 发布:淘宝联盟一直不提现 编辑:程序博客网 时间:2024/06/13 23:28

基数排序(radix sort)属于“分配式排序”(distribution sort),又称“桶子法”(bucket sort)或bin sort,顾名思义,它是透过键值的部份资讯,将要排序的元素分配至某些“桶”中,藉以达到排序的作用,基数排序法是属于稳定性的排序,其时间复杂度为O (nlog(r)m),其中r为所采取的基数,而m为堆数,在某些时候,基数排序法的效率高于其它的稳定性排序法。


基本解法

第一步

以LSD为例,假设原来有一串数值如下所示:
73, 22, 93, 43, 55, 14, 28, 65, 39, 81
首先根据个位数的数值,在走访数值时将它们分配至编号0到9的桶子中:
0
1 81
2 22
3 73 93 43
4 14
5 55 65
6
7
8 28
9 39

第二步

接下来将这些桶子中的数值重新串接起来,成为以下的数列:
81, 22, 73, 93, 43, 14, 55, 65, 28, 39
接着再进行一次分配,这次是根据十位数来分配:
0
1 14
2 22 28
3 39
4 43
5 55
6 65
7 73
8 81
9 93

第三步


接下来将这些桶子中的数值重新串接起来,成为以下的数列:
14, 22, 28, 39, 43, 55, 65, 73, 81, 93
这时候整个数列已经排序完毕;如果排序的对象有三位数以上,则持续进行以上的动作直至最高位数为止。
LSD的基数排序适用于位数小的数列,如果位数多的话,使用MSD的效率会比较好。MSD的方式与LSD相反,是由高位数为基底开始进行分配,但在分配之后并不马上合并回一个数组中,而是在每个“桶子”中建立“子桶”,将每个桶子中的数值按照下一数位的值分配到“子桶”中。在进行完最低位数的分配后再合并回单一的数组中。

import java.util.ArrayList;public class RadixSort {public static void main(String[] args) {RadixSort radixSort = new RadixSort();int[] a = { 19, 2, 3, 90, 67, 33, 7, 24, 3, 56, 34, 5, 65,0 };radixSort.sort(a);for (int num : a) {System.out.println(" " + num);}}private void sort(int[] a) {// TODO Auto-generated method stub//获取最大值int max = 0;if (a.length > 0) {for (int i = 0; i < a.length; i++) {if (max < a[i])max = a[i];}}//获取循环的次数String maxString = max+"";int times= maxString.length();     for (int i = 0; i < times; i++) {     int start=0;     //放十个容器     ArrayList<ArrayList> queueList = new ArrayList<ArrayList>();for (int j = 0; j < 10; j++) {queueList.add(new ArrayList<>());}for (int j = 0; j < a.length; j++) {int index = a[j]%(int)Math.pow(10, i+1)/(int)Math.pow(10, i);ArrayListarray = queueList.get(index);array.add(a[j]);}for (int j = 0; j < 10; j++) {ArrayList arrayList=queueList.get(j);for (int k = 0; k < arrayList.size(); k++) {a[start++] = (int) arrayList.get(k);}}}     }}



1 0
原创粉丝点击