|
1 | 1 | package com.thealgorithms.sorts; |
2 | 2 |
|
| 3 | +import java.util.ArrayList; |
3 | 4 | import java.util.Arrays; |
| 5 | +import java.util.List; |
4 | 6 |
|
5 | 7 | /** |
6 | 8 | * Double Hashing Sort Algorithm Implementation |
@@ -41,40 +43,30 @@ public <T extends Comparable<T>> T[] sort(T[] array) { |
41 | 43 | * @return sorted array |
42 | 44 | */ |
43 | 45 | 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); |
50 | 48 | 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<>()); |
55 | 50 | } |
56 | 51 |
|
57 | 52 | // Distribute elements into buckets using double hashing |
58 | 53 | for (T element : array) { |
59 | 54 | int bucketIndex = getBucketIndex(element, bucketCount); |
60 | | - buckets[bucketIndex][bucketSizes[bucketIndex]++] = element; |
| 55 | + buckets.get(bucketIndex).add(element); |
61 | 56 | } |
62 | 57 |
|
63 | 58 | // Sort each bucket and collect results |
64 | 59 | int index = 0; |
65 | 60 | 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 | + } |
78 | 70 | } |
79 | 71 | } |
80 | 72 |
|
|
0 commit comments