八大内部排序算法(中)-基数排序(java实现)

来源:互联网 发布:网口数据监控软件 编辑:程序博客网 时间:2024/06/01 08:34

基数排序理论很好理解,基本思想就是:将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。

对于基数排序有两种方法:

最高位优先法(MSD)(Most Significant Digit first)

最低位优先法(LSD)(Least Significant Digit first)

基数排序是稳定的排序算法,它的平均时间复杂程度为:O(d(r+n)),空间复杂度为:O(rd+n)。

它的实现自己这么多年来一直没去写,今天抽了点时间出来,参考了网上的一些大神们还有书上的算法过程,专门对基数排序做了个Java代码的实现,采取的是从低位到高位的排序方式,源代码如下:

package com.devin.sequence;import java.util.Arrays;/**  * * @JavaTest * @author  ldw  * @date    创建时间:2015年4月24日 下午7:15:47  * @version 2015年4月24日   * */public class RadixSort {public static void main(String[] args) {  Integer[] array = new Integer[] { 1200, 292, 121, 72, 233, 44, 12 };  radixSort(array, 10, 4);          System.out.println("排序后的数组:");          print(array);      }    /* * 8.基数排序  稳定的排序算法   * array代表数组 * radix 代表基数 * d代表排序元素的位数 */public static void radixSort(Integer []array, int radix, int d){// 临时数组          Integer[] tempArray = new Integer[array.length];          // count用于记录待排序元素的信息,用来表示该位是i的数的个数          Integer[] count = new Integer[radix];            int rate = 1;        for (int i = 0; i < d; i++) {              //重置count数组,开始统计下一个关键字              Arrays.fill(count, 0);            //将array中的元素完全复制到tempArray数组中              System.arraycopy(array, 0, tempArray, 0, array.length);                //计算每个待排序数据的子关键字              for (int j = 0; j < array.length; j++) {                  int subKey = (tempArray[j] / rate) % radix;                  count[subKey]++;            }              //统计count数组的前j位(包含j)共有多少个数            for (int j = 1; j < radix; j++) {              count[j] = count[j] + count[j - 1];             }              //按子关键字对指定的数据进行排序 ,因为开始是从前往后放,现在从后忘前读取,保证基数排序的稳定性            for (int m = array.length - 1; m >= 0; m--) {                  int subKey = (tempArray[m] / rate) % radix;                  array[--count[subKey]] = tempArray[m]; //插入到第--count[subKey]位,因为数组下标从0开始            }              rate *= radix;//前进一位              System.out.print("第" + (i+1) + "次:");            print(array);        }  }//输出数组===============public static void print(Integer[] array) {          for (int i = 0; i < array.length; i++) {              System.out.print(array[i] + "\t");          }          System.out.println();      }  }


测试结果:

第1次:1200121292721223344第2次:1200121212334472292第3次:1244721211200233292第4次:1244721212332921200排序后的数组:1244721212332921200



1 0