基数排序的java实现

来源:互联网 发布:电商运营数据分析表格 编辑:程序博客网 时间:2024/05/16 15:39
        前几天师兄问我基数排序怎么实现,原理我很清楚啊,就给他说了,但是当他详细问道用具体的计数排序怎样实现时,我尽然没有详细的实现思路。今天有空就把它实现了。不懂理论不行,但是光知道一点理论知识,不去动手实践是不行的,以后还是要多思,多做。

       详细代码如下:

package com.algorithm.sort;import java.util.Arrays;public class RadixSort {//基于计数排序的基数排序算法private static void radixSort(int[] array,int radix, int distance) {//array为待排序数组//radix,代表基数//代表排序元素的位数int length = array.length;int[] temp = new int[length];//用于暂存元素int[] count = new int[radix];//用于计数排序int divide = 1;for (int i = 0; i < distance; i++) {System.arraycopy(array, 0,temp, 0, length);Arrays.fill(count, 0);for (int j = 0; j < length; j++) {int tempKey = (temp[j]/divide)%radix;count[tempKey]++;}for (int j = 1; j < radix; j++) {count [j] = count[j] + count[j-1];}//个人觉的运用计数排序实现计数排序的重点在下面这个方法for (int j = length - 1; j >= 0; j--) {int tempKey = (temp[j]/divide)%radix;count[tempKey]--;array[count[tempKey]] = temp[j];}divide = divide * radix;}}/** * @param args */public static void main(String[] args) {int[] array = {3,2,3,2,5,333,45566,2345678,78,990,12,432,56};radixSort(array,10,7);for (int i = 0; i < array.length; i++) {System.out.print("  " + array[i]);}}}