Skip to content

Commit d070a54

Browse files
author
Alex Klymenko
committed
fix: extracting logic to separate methods to improve readability
1 parent d0fb1ba commit d070a54

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/main/java/com/thealgorithms/sorts/CountingSort.java

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,22 +28,26 @@ public <T extends Comparable<T>> T[] sort(T[] array) {
2828
*/
2929
@Override
3030
public <T extends Comparable<T>> List<T> sort(List<T> list) {
31-
// TreeMap to maintain order of elements naturally.
32-
Map<T, Integer> frequencyMap = new TreeMap<>();
33-
34-
// Count the frequency of each element in the list.
35-
for (T element : list) {
36-
frequencyMap.put(element, frequencyMap.getOrDefault(element, 0) + 1);
37-
}
31+
Map<T, Integer> frequencyMap = computeHistogramMap(list);
32+
return formSortedArrayFromHistogramMap(list, frequencyMap);
33+
}
3834

39-
// Create the sorted list based on the frequency map.
35+
private static <T extends Comparable<T>> List<T> formSortedArrayFromHistogramMap(List<T> list, Map<T, Integer> frequencyMap) {
4036
List<T> sortedList = new ArrayList<>(list.size());
4137
for (Map.Entry<T, Integer> entry : frequencyMap.entrySet()) {
4238
for (int i = 0; i < entry.getValue(); i++) {
4339
sortedList.add(entry.getKey());
4440
}
4541
}
46-
4742
return sortedList;
4843
}
44+
45+
private static <T extends Comparable<T>> Map<T, Integer> computeHistogramMap(List<T> list) {
46+
// TreeMap to maintain order of elements naturally.
47+
Map<T, Integer> frequencyMap = new TreeMap<>();
48+
for (T element : list) {
49+
frequencyMap.put(element, frequencyMap.getOrDefault(element, 0) + 1);
50+
}
51+
return frequencyMap;
52+
}
4953
}

0 commit comments

Comments
 (0)