Skip to content

Commit 2532017

Browse files
author
wangzheng
committed
14_sorts
1 parent 53a608e commit 2532017

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

java/14_sorts/CountingSort.java

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package sorts;
2+
3+
/**
4+
* 计数排序
5+
*
6+
* Author: ZHENG
7+
*/
8+
public class CountingSort {
9+
10+
// 计数排序,a是数组,n是数组大小。假设数组中存储的都是非负整数。
11+
public static void countingSort(int[] a, int n) {
12+
if (n <= 1) return;
13+
14+
// 查找数组中数据的范围
15+
int max = a[0];
16+
for (int i = 1; i < n; ++i) {
17+
if (max < a[i]) {
18+
max = a[i];
19+
}
20+
}
21+
22+
// 申请一个计数数组c,下标大小[0,max]
23+
int[] c = new int[max + 1];
24+
for (int i = 0; i < max + 1; ++i) {
25+
c[i] = 0;
26+
}
27+
28+
// 计算每个元素的个数,放入c中
29+
for (int i = 0; i < n; ++i) {
30+
c[a[i]]++;
31+
}
32+
33+
// 依次累加
34+
for (int i = 1; i < max + 1; ++i) {
35+
c[i] = c[i-1] + c[i];
36+
}
37+
38+
// 临时数组r,存储排序之后的结果
39+
int[] r = new int[n];
40+
// 计算排序的关键步骤了,有点难理解
41+
for (int i = n - 1; i >= 0; --i) {
42+
int index = c[a[i]]-1;
43+
r[index] = a[i];
44+
c[a[i]]--;
45+
}
46+
47+
// 将结果拷贝会a数组
48+
for (int i = 0; i < n; ++i) {
49+
a[i] = r[i];
50+
}
51+
}
52+
53+
}

0 commit comments

Comments
 (0)