- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCountingSort.java
More file actions
Latest commit
32 lines (26 loc) · 1.04 KB
/
Copy pathCountingSort.java
File metadata and controls
32 lines (26 loc) · 1.04 KB
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
29
30
31
32
/**
* An implementation of counting sort!
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
packageSorting;
publicclassCountingSort {
// Sorts values in the range of [minVal, maxVal] in O(n+maxVal-maxVal)
publicstaticvoidcountingSort(int[] ar, intminVal, intmaxVal) {
intsz = maxVal - minVal + 1;
int[] B = newint[sz];
for (inti = 0; i < ar.length; i++) B[ar[i] - minVal]++;
for (inti = 0, k = 0; i < sz; i++) while (B[i]-- > 0) ar[k++] = i + minVal;
}
publicstaticvoidmain(String[] args) {
// The maximum and minimum values on the numbers we are sorting.
// You need to know ahead of time the upper and lower bounds on
// the numbers you are sorting for counting sort to work.
finalintMIN_VAL = -10;
finalintMAX_VAL = +10;
int[] nums = {+4, -10, +0, +6, +1, -5, -5, +1, +1, -2, 0, +6, +8, -7, +10};
countingSort(nums, MIN_VAL, MAX_VAL);
// prints [-10, -7, -5, -5, -2, 0, 0, 1, 1, 1, 4, 6, 6, 8, 10]
System.out.println(java.util.Arrays.toString(nums));
}
}