MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / sort

Method sort

src/main/java/com/thealgorithms/sorts/DarkSort.java:17–42  ·  view source on GitHub ↗

Sorts the array using the Dark Sort algorithm. @param unsorted the array to be sorted @return sorted array

(Integer[] unsorted)

Source from the content-addressed store, hash-verified

15 * @return sorted array
16 */
17 public Integer[] sort(Integer[] unsorted) {
18 if (unsorted == null || unsorted.length <= 1) {
19 return unsorted;
20 }
21
22 int max = findMax(unsorted); // Find the maximum value in the array
23
24 // Create a temporary array for counting occurrences
25 int[] temp = new int[max + 1];
26
27 // Count occurrences of each element
28 for (int value : unsorted) {
29 temp[value]++;
30 }
31
32 // Reconstruct the sorted array
33 int index = 0;
34 for (int i = 0; i < temp.length; i++) {
35 while (temp[i] > 0) {
36 unsorted[index++] = i;
37 temp[i]--;
38 }
39 }
40
41 return unsorted;
42 }
43
44 /**
45 * Helper method to find the maximum value in an array.

Callers 6

testSortWithIntegersMethod · 0.95
testEmptyArrayMethod · 0.95
testNullArrayMethod · 0.95

Calls 1

findMaxMethod · 0.95

Tested by 6

testSortWithIntegersMethod · 0.76
testEmptyArrayMethod · 0.76
testNullArrayMethod · 0.76