算法思路
桶排序是计数排序的扩展版本,计数排序可以看成每个桶只存储相同元素,而桶排序每个桶存储一定范围的元素,通过映射函数,将待排序数组中的元素映射到各个对应的桶中,对每个桶中的元素进行排序,最后将非空桶中的元素逐个放入原序列中。
代码
/**
* @description:桶排序 数组实现时间复杂度为o(n方) 可以使用队列降低时间复杂度并且保证排序稳定
* @Author MRyan
* @Date 2020/5/15 16:57
* @Version 1.0
*/
public class Barrel_Sort {
public static void main(String[] args) {
int[] nums = {3, 2, 5, 0, 4};
sort(nums);
}
/**
* 待排序数组 {3, 2, 5, 0, 4};
* 给定待排序的数组中数值大小0-5 所以我们准备6个桶,分别代表数字 0 1 2 3 4 5
* 桶群记录数组中每个元素出现的次数 1 0 1 1 1 1
* 待排数组种有1个0则0下标的值为1 待排序数组有0个1则1下标值为0
* 然后从桶群中按顺序依次取出相应数量的值 也就是 0 2 3 4 5 排序结束
* 桶排序是一个概念,可以是数组 队列 栈 链表实现
*
* @param nums
*/
public static void sort(int[] nums) {
//找到数组中的最大值 确定桶群范围
int max = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
max = Math.max(max, nums[i]);
}
//这个例子桶群大小就 6
int[] help = new int[max + 1];
int[] answer = new int[nums.length];
//answer数组下标
int n = 0;
//数组数值加入对应桶
for (int i : nums) {
help[i]++;
}
//导出桶中的元素
for (int i = 0; i < help.length; i++) {
int j = help[i];
while (j > 0) {
answer[n++] = i;
j--;
}
}
print_nums(answer);
}
public static void print_nums(int[] nums) {
for (int i : nums) {
System.out.print(i + " ");
}
}
}