赞
踩
桶排序是将待排序集合中处于同一个值域的元素存入同一个桶中,(当然这个桶的存储结构也是多样的,可以是数组、栈、队列啊等等)也就是根据元素值特性将集合拆分为多个区域,则拆分后形成的多个桶,从值域上看是处于有序状态的。对每个桶中元素进行排序,则所有桶中元素构成的集合是已排序的。
那么从本质上来讲,桶排序和其它排序方法最大的不同之处在于:
桶排序是不基于比较的排序
下面举两个具体的实现来验证一下
需求:现需要对某公司的员工按照年龄由小到大的顺序排序;
那么我们可以采用计数排序,由于人类的年龄是不可能超过150岁的。
那么我们就可以创建一个下标为0~150的数组,下标对应的就是年龄,那么遍历所有员工的年龄信息,加入出现一个年龄为18岁的员工,那么下标为18的值++,循环结束后我们就可以得到一个记录着所有年龄人数的数组,最后我们再遍历输出即可完成排序。
具体代码实现如下:
public static void countSort(int[] arr) { if (arr == null || arr.length < 2) { return; } //找出arr中最大的一个数 int max = Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { max = Math.max(max, arr[i]); } //确定桶的大小 int[] bucket = new int[max + 1]; for (int i = 0; i < arr.length; i++) { bucket[arr[i]]++; } //最后遍历输出 int i = 0; for (int j = 0; j < bucket.length; j++) { while (bucket[j]-- > 0) { arr[i++] = j; } } }
通过代码的实现,我们可以发现,桶排序确实是没有经过一次排序。
首先这种排序方法适用于对十进制的正整数进行排序。
原理如下:
需求:对[101,200,12,11,202,403]按照从小到大进行排序。
首先发现这个数组中最大的数是三位数,那么我们都把这些数补成都是三位数的形式:[101,200,012,011,202,403]
1)首先按照个位数字来依次进桶,个位数字为0就进0号桶,为3就进3号桶
2)然后再按照十位数字来依次进桶
3)再按照百位数字来依次进桶
。。。。。。
且每个桶都是一个队列结构,讲究先进先出。
在具体的代码实现中呢,我们没有必要去建那么多的桶结构来帮助排序,这样空间复杂度就会很高。
我们可以优化一下,但是原理还是跟上面说的一样。
还是[101,200,12,11,202,403]
具体代码实现如下:
public static void radixSort(int[] arr) { if (arr == null || arr.length < 2) { return; } radixSort(arr, 0, arr.length - 1, maxbits(arr)); } public static int maxbits(int[] arr) { int max = Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { max = Math.max(max, arr[i]); } int res = 0; while (max != 0) { res++; max /= 10; } return res; } // arr[L..R]排序 , 最大值的十进制位数digit public static void radixSort(int[] arr, int L, int R, int digit) { final int radix = 10; int i = 0, j = 0; // 有多少个数准备多少个辅助空间 int[] help = new int[R - L + 1]; for (int d = 1; d <= digit; d++) { // 有多少位就进出几次 // 10个空间 // count[0] 当前位(d位)是0的数字有多少个 // count[1] 当前位(d位)是(0和1)的数字有多少个 // count[2] 当前位(d位)是(0、1和2)的数字有多少个 // count[i] 当前位(d位)是(0~i)的数字有多少个 int[] count = new int[radix]; // count[0..9] for (i = L; i <= R; i++) { // 103 1 3 // 209 1 9 j = getDigit(arr[i], d); count[j]++; } for (i = 1; i < radix; i++) { count[i] = count[i] + count[i - 1]; } for (i = R; i >= L; i--) { j = getDigit(arr[i], d); help[count[j] - 1] = arr[i]; count[j]--; } for (i = L, j = 0; i <= R; i++, j++) { arr[i] = help[j]; } } } public static int getDigit(int x, int d) { return ((x / ((int) Math.pow(10, d - 1))) % 10); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。