|
| 1 | +// Java program to sort an array |
| 2 | +// using bucket sort |
| 3 | +import java.util.*; |
| 4 | +import java.util.Collections; |
| 5 | + |
| 6 | +class GFG { |
| 7 | + |
| 8 | + // Function to sort arr[] of size n |
| 9 | + // using bucket sort |
| 10 | + static void bucketSort(float arr[], int n) |
| 11 | + { |
| 12 | + if (n <= 0) |
| 13 | + return; |
| 14 | + |
| 15 | + // 1) Create n empty buckets |
| 16 | + @SuppressWarnings("unchecked") |
| 17 | + Vector<Float>[] buckets = new Vector[n]; |
| 18 | + |
| 19 | + for (int i = 0; i < n; i++) { |
| 20 | + buckets[i] = new Vector<Float>(); |
| 21 | + } |
| 22 | + |
| 23 | + // 2) Put array elements in different buckets |
| 24 | + for (int i = 0; i < n; i++) { |
| 25 | + float idx = arr[i] * n; |
| 26 | + buckets[(int)idx].add(arr[i]); |
| 27 | + } |
| 28 | + |
| 29 | + // 3) Sort individual buckets |
| 30 | + for (int i = 0; i < n; i++) { |
| 31 | + Collections.sort(buckets[i]); |
| 32 | + } |
| 33 | + |
| 34 | + // 4) Concatenate all buckets into arr[] |
| 35 | + int index = 0; |
| 36 | + for (int i = 0; i < n; i++) { |
| 37 | + for (int j = 0; j < buckets[i].size(); j++) { |
| 38 | + arr[index++] = buckets[i].get(j); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + // Driver code |
| 44 | + public static void main(String args[]) |
| 45 | + { |
| 46 | + float arr[] = { (float)0.897, (float)0.565, |
| 47 | + (float)0.656, (float)0.1234, |
| 48 | + (float)0.665, (float)0.3434 }; |
| 49 | + |
| 50 | + int n = arr.length; |
| 51 | + bucketSort(arr, n); |
| 52 | + |
| 53 | + System.out.println("Sorted array is "); |
| 54 | + for (float el : arr) { |
| 55 | + System.out.print(el + " "); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +// This code is contributed by Himangshu Shekhar Jha |
0 commit comments