Skip to content

Commit febf9cc

Browse files
committed
Fix DoubleHashingSort compilation warnings - use ArrayList instead of generic arrays
1 parent d1cf92f commit febf9cc

File tree

1 file changed

+15
-23
lines changed

1 file changed

+15
-23
lines changed

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

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.thealgorithms.sorts;
22

3+
import java.util.ArrayList;
34
import java.util.Arrays;
5+
import java.util.List;
46

57
/**
68
* Double Hashing Sort Algorithm Implementation
@@ -41,40 +43,30 @@ public <T extends Comparable<T>> T[] sort(T[] array) {
4143
* @return sorted array
4244
*/
4345
private <T extends Comparable<T>> T[] doubleHashingSort(T[] array, int bucketCount) {
44-
// Create buckets
45-
@SuppressWarnings("unchecked")
46-
T[][] buckets = (T[][]) new Comparable[bucketCount][];
47-
int[] bucketSizes = new int[bucketCount];
48-
49-
// Initialize buckets
46+
// Create buckets using ArrayList to avoid generic array issues
47+
List<List<T>> buckets = new ArrayList<>(bucketCount);
5048
for (int i = 0; i < bucketCount; i++) {
51-
@SuppressWarnings("unchecked")
52-
T[] bucket = (T[]) new Comparable[array.length];
53-
buckets[i] = bucket;
54-
bucketSizes[i] = 0;
49+
buckets.add(new ArrayList<>());
5550
}
5651

5752
// Distribute elements into buckets using double hashing
5853
for (T element : array) {
5954
int bucketIndex = getBucketIndex(element, bucketCount);
60-
buckets[bucketIndex][bucketSizes[bucketIndex]++] = element;
55+
buckets.get(bucketIndex).add(element);
6156
}
6257

6358
// Sort each bucket and collect results
6459
int index = 0;
6560
for (int i = 0; i < bucketCount; i++) {
66-
if (bucketSizes[i] > 0) {
67-
// Create actual sized array for this bucket
68-
@SuppressWarnings("unchecked")
69-
T[] bucket = (T[]) new Comparable[bucketSizes[i]];
70-
System.arraycopy(buckets[i], 0, bucket, 0, bucketSizes[i]);
71-
72-
// Sort the bucket
73-
Arrays.sort(bucket);
74-
75-
// Copy back to main array
76-
System.arraycopy(bucket, 0, array, index, bucketSizes[i]);
77-
index += bucketSizes[i];
61+
List<T> bucket = buckets.get(i);
62+
if (!bucket.isEmpty()) {
63+
// Sort the bucket directly using Collections.sort
64+
bucket.sort(null);
65+
66+
// Copy sorted elements back to main array
67+
for (T element : bucket) {
68+
array[index++] = element;
69+
}
7870
}
7971
}
8072

0 commit comments

Comments
 (0)