算法思路
桶排序是計數排序的擴展版本,計數排序可以看成每個桶只存儲相同元素,而桶排序每個桶存儲一定範圍的元素,通過映射函數,將待排序數組中的元素映射到各個對應的桶中,對每個桶中的元素進行排序,最後將非空桶中的元素逐個放入原序列中。
代碼
/**
* @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 + " ");
}
}
}