* - 根据待排数据分布情况设置一定数量桶 * - 根据一定函数规则将数据映射进对应的桶中 * - 分别采用其他排序算法对桶进行排序 * - 对有数据的桶取出后进行拼接合并 *
* * @author lyd Date 2019/4/7 ProjectName:datastructure-algo Version: 1.0 */ @Slf4j public class BucketSort { /** * 桶排序 * * @param data 待排数据集 * @return 排序后数据集 */ static int[] bucketSort(int[] data) { if (null == data || data.length < 1) { return data; } //找出待排序数列中最大值和最小值,通过最大元素和最小元素跨度值来计算需要多少个桶 int min = data[0]; int max = data[0]; for (int i = 1; i < data.length; i++) { if (data[i] < min) { min = data[i]; } if (data[i] > max) { max = data[i]; } } //都是相同元素 if (min == max) { return data; } //计算桶数量 int bucketCount = (int) ((Math.floor((max - min) / data.length)) + 1); //定义一个二维数组,存储每个桶和每个桶中对应的数据集(这里每个桶的容量也可以用链表来实现) int[][] buckets = new int[bucketCount][0]; log.info("call bucketSort length:{},min:{},max:{},bucketCount:{}", data.length, min, max, bucketCount); //将每个元素值情况计算后放入对应的桶中 for (int i = 0; i < data.length; i++) { //计算出元素映射桶的下标索引:当前元素和最小元素差 除 桶个数 取整 int bucketIndex = (int) (Math.floor((data[i] - min) / data.length)); //动态扩增桶大小 int[] temp = Arrays.copyOf(buckets[bucketIndex], buckets[bucketIndex].length + 1); temp[temp.length - 1] = data[i]; buckets[bucketIndex] = temp; } //针对桶中数据进行再排序 int sortIndex = 0; for (int i = 0; i < bucketCount; i++) { //采用快速排序 if (buckets[i].length > 0) { int[] temp = QuickSort.quickSort(buckets[i]); for (int j = 0; j < temp.length; j++) { data[sortIndex++] = temp[j]; } } } return data; } public static void main(String[] args) { // int[] sorts = new int[]{13, 15, 13, 5, 6, 11, 16, 20, 17, 12, 5, 6, 11, 16, 20, 17}; int[] sorts = RandomUtils.intArrays(4, 100); int[] result = bucketSort(sorts); log.info("sorts:{}", result);//[5, 5, 6, 6, 11, 11, 12, 13, 13, 15, 16, 16, 17, 17, 20, 20] } } ```相关文章: