| 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) { |