-
Notifications
You must be signed in to change notification settings - Fork 88
/
RadixSortOptimized.java
57 lines (47 loc) · 1.74 KB
/
RadixSortOptimized.java
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RadixSortOptimized {
public static void radixSort(Object[] arr) {
if (arr == null || arr.length == 0) {
return;
}
// Find the maximum value to determine the number of digits
double max = (double) arr[0];
for (Object item : arr) {
if ((double) item > max) {
max = (double) item;
}
}
// Perform counting sort for each digit position
int exp = 1;
List<Object>[] buckets = new ArrayList[10];
for (int i = 0; i < buckets.length; i++) {
buckets[i] = new ArrayList<>();
}
while (max / exp >= 1) {
// Place elements into buckets based on the current digit
for (Object item : arr) {
int index = (int) (((double) item / exp) % 10);
buckets[index].add(item);
}
// Copy elements from buckets back to the original array
int currentIndex = 0;
for (List<Object> bucket : buckets) {
for (Object item : bucket) {
arr[currentIndex++] = item;
}
bucket.clear();
}
// Move to the next digit position
exp *= 10;
}
}
public static void main(String[] args) {
// Example usage with both integers and non-integers
Object[] arr = {5, 2.3, 10.1, 3.7, 8, 1.2, 4.5};
System.out.println("Before sorting: " + Arrays.toString(arr));
radixSort(arr);
System.out.println("After sorting: " + Arrays.toString(arr));
}
}