| 3 | import java.util.Collections; |
| 4 | |
| 5 | public class BucketSort { |
| 6 | public void bucketSort(float[] arr, int n) { |
| 7 | if (n <= 0) |
| 8 | return; |
| 9 | @SuppressWarnings("unchecked") |
| 10 | ArrayList<Float>[] bucket = new ArrayList[n]; |
| 11 | |
| 12 | // Create empty buckets |
| 13 | for (int i = 0; i < n; i++) |
| 14 | bucket[i] = new ArrayList<Float>(); |
| 15 | |
| 16 | // Add elements into the buckets |
| 17 | for (int i = 0; i < n; i++) { |
| 18 | int bucketIndex = (int) arr[i] * n; |
| 19 | bucket[bucketIndex].add(arr[i]); |
| 20 | } |
| 21 | |
| 22 | // Sort the elements of each bucket |
| 23 | for (int i = 0; i < n; i++) { |
| 24 | Collections.sort((bucket[i])); |
| 25 | } |
| 26 | |
| 27 | // Get the sorted array |
| 28 | int index = 0; |
| 29 | for (int i = 0; i < n; i++) { |
| 30 | for (int j = 0, size = bucket[i].size(); j < size; j++) { |
| 31 | arr[index++] = bucket[i].get(j); |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | // Driver code |
| 37 | public static void main(String[] args) { |
| 38 | BucketSort b = new BucketSort(); |
| 39 | float[] arr = { (float) 0.42, (float) 0.32, (float) 0.33, (float) 0.52, (float) 0.37, (float) 0.47, |
| 40 | (float) 0.51 }; |
| 41 | b.bucketSort(arr, 7); |
| 42 | |
| 43 | for (float i : arr) |
| 44 | System.out.print(i + " "); |
| 45 | } |
| 46 | } |
nothing calls this directly
no outgoing calls
no test coverage detected