-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCounting_sort.java
More file actions
27 lines (22 loc) · 898 Bytes
/
Copy pathCounting_sort.java
File metadata and controls
27 lines (22 loc) · 898 Bytes
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
import java.util.*;
public class Counting_sort {
public static ArrayList<Integer> sort(ArrayList<Integer> arr) {
int maxValue = Collections.max(arr);
int minValue = Collections.min(arr);
ArrayList<Integer> count = new ArrayList<>(Collections.nCopies(maxValue - minValue + 1, 0));
for(int num : arr){
int j = num - minValue;
count.set(j, count.get(j) + 1);
}
ArrayList<Integer> SortedArr = new ArrayList<>();
// Build the sorted array from count array
//int totalvalue = minValue + maxValue;
for (int i = minValue; i <= maxValue; i++) {
while (count.get(i -minValue) > 0) {
SortedArr.add(i + minValue);
count.set(i - minValue, count.get(i - minValue) - 1);
}
}
return SortedArr;
}
}