Sorts the array using the Dark Sort algorithm. @param unsorted the array to be sorted @return sorted array
(Integer[] unsorted)
| 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. |