# 计数排序

十大常用的排序算法中，这三种算法都用到了桶的概念

• 基数排序：根据键值的每位数字来分配桶；
• 计数排序：每个桶只存储单一键值；
• 桶排序：每个桶存储一定范围的数值；
 1 public class MyCountSort {
2     public static void main(String[] args) {
3         int num[] = {10, 10, 33, 54, 33, 6, 6, 7, 3, 3};
4         countingSort(num);
5     }
6
7     private static void countingSort(int[] num) {
8         int min = num[0];
9         int max = num[0];
10         for (int i = 0; i < num.length; i++) {
11             if (num[i] > max) {
12                 max = num[i];
13             }
14             if (num[i] < min) {
15                 min = num[i];
16             }
17         }
18         int offset = 0 - min;
19         int count[] = new int[max - min + 1];
20         for (int i = 0; i < num.length; i++) {
21             count[num[i] + offset]++;
22         }
23         for (int i = 0; i < count.length; i++) {
24             while (count[i] > 0) {
25                 System.out.print(i - offset + " ");
26                 count[i]--;
27             }
28         }
29     }
30 }
View Code

posted on 2020-07-23 09:44  含光Aries  阅读(140)  评论(0编辑  收藏  举报