# 算法 - 计数排序

 1 public class CountSort {
2
3     public void sort(int[] arr) {
4         printArr(arr, " => 原数组");
5         // 确认最大最小值
6         int max = arr[0];
7         int min = arr[0];
8         for (int i = 1; i < arr.length; i++) {
9             if (arr[i] > max) {
10                 max = arr[i];
11             }
12             if (arr[i] < min) {
13                 min = arr[i];
14             }
15         }
16         // 根据最大最小值创建数组
17         int length = max - min + 2;
18         int[] countArr = new int[length];
19         printArr(countArr, " => 计数数组");
20         // 处理有负数的情况
21         int zeroIndex = 0;
22         if (min < 0) {
23             zeroIndex = min * -1;
24         }
25         // 计数
26         for (int i = 0; i < arr.length; i++) {
27             if (zeroIndex > 0) {
28                 countArr[arr[i] + zeroIndex]++;
29             } else {
30                 countArr[arr[i]]++;
31             }
32         }
33         printArr(countArr, " => 完成计数");
34         // 给原数组赋值
35         int index = 0;
36         for (int i = 0; i < countArr.length; i++) {
37             while (countArr[i]-- > 0) {
38                 if (zeroIndex > 0) {
39                     arr[index++] = i - zeroIndex;
40                     continue;
41                 }
42                 arr[index++] = i;
43             }
44         }
45         printArr(arr, " => 完成赋值");
46     }
47
48     private void printArr(int[] arr, String message) {
49         for (int i : arr) {
50             System.out.print(i + ",");
51         }
52         System.out.println(message);
53     }
54
55     public static void main(String[] args) {
56         CountSort cs = new CountSort();
57         int[] arr = new int[]{-1, 3, -5, 7, 8, 0, 5, 7, 11};
58         cs.sort(arr);
59     }
60
61     /**
62      * -1,3,-5,7,8,0,5,7,11 => 原数组
63      * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 => 计数数组
64      * 1,0,0,0,1,1,0,0,1,0,1,0,2,1,0,0,1,0 => 完成计数
65      * -5,-1,0,3,5,7,7,8,11 => 完成赋值
66      *
67      * 利用空间换时间的想法
68      * => 遍历次数为m+m+k，m为原数组，k为计数数组
69      * => 时间复杂度：O(n)
70      * => 稳定性：稳定 => 都是整数
71      */
72
73 }

posted @ 2020-04-30 11:12  SamNicole1809  阅读(58)  评论(0编辑  收藏