bucket sort algorithm java

Solutions on MaxInterview for bucket sort algorithm java by the best coders in the world

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