forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDarkSort.java
More file actions
59 lines (51 loc) · 1.41 KB
/
DarkSort.java
File metadata and controls
59 lines (51 loc) · 1.41 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.thealgorithms.sorts;
/**
* Dark Sort algorithm implementation.
*
* Dark Sort uses a temporary array to count occurrences of elements and
* reconstructs the sorted array based on the counts.
*/
class DarkSort {
/**
* Sorts the array using the Dark Sort algorithm.
*
* @param unsorted the array to be sorted
* @return sorted array
*/
public Integer[] sort(Integer[] unsorted) {
if (unsorted == null || unsorted.length <= 1) {
return unsorted;
}
int max = findMax(unsorted); // Find the maximum value in the array
// Create a temporary array for counting occurrences
int[] temp = new int[max + 1];
// Count occurrences of each element
for (int value : unsorted) {
temp[value]++;
}
// Reconstruct the sorted array
int index = 0;
for (int i = 0; i < temp.length; i++) {
while (temp[i] > 0) {
unsorted[index++] = i;
temp[i]--;
}
}
return unsorted;
}
/**
* Helper method to find the maximum value in an array.
*
* @param arr the array
* @return the maximum value
*/
private int findMax(Integer[] arr) {
int max = arr[0];
for (int value : arr) {
if (value > max) {
max = value;
}
}
return max;
}
}