Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

Counting sort

Posted on 2020-05-09 | Edited on 2020-05-20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.*;

public class Counting_sort {
static int[] countingSort(int[] a) {
int maxValue=0;
for (int i : a) maxValue=i>maxValue?i:maxValue;

int c[] = new int[maxValue + 1];
for (int i = 0; i < a.length; i++) c[a[i]]++;

int b[] = new int[a.length];

int count = 0;
for (int i = 0; i <= maxValue; i++) {
while (c[i] > 0) {
b[count++] = i;
c[i]--;
}
}
return b;
}

// *********************************************
public static void main(String[] args) {
int[] arr = { 2, 5, 8, 0, 4, 2, 1 };
System.out.println(Arrays.toString(countingSort(arr)));
}
}
<1…219220221…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%