java bucket sort

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

showing results for - "java bucket sort"
Azariah
17 May 2018
1public class Main 
2{
3   public static int[] bucket_sort(int[] arr, int max_value) 
4    {
5        int[] bucket = new int[max_value + 1];
6        int[] sorted_arr = new int[arr.length];
7 
8        for (int i= 0; i <arr.length; i++)
9            bucket[arr[i]]++;
10 
11        int pos = 0;
12        for (int i = 0; i < bucket.length; i++)
13            for (int j = 0; j < bucket[i]; j++)
14                sorted_arr[pos++] = i;
15 
16        return sorted_arr;
17    }
18 
19 
20    static int maxValue(int[] arr) 
21    {
22        int max_value = 0;
23        for (int i = 0; i < arr.length; i++)
24            if (arr[i] > max_value)
25                max_value = arr[i];
26        return max_value;
27    }
28 
29    public static void main(String args[]) 
30    {
31        int[] arr ={80, 50, 30, 10, 90, 60, 0, 70, 40, 20, 50};
32        int max_value = maxValue(arr);
33 
34        System.out.print("\nOriginal : ");
35        System.out.println(Arrays.toString(arr));
36 
37        System.out.print("\nSorted : ");
38        System.out.println(Arrays.toString(bucket_sort(arr,max_value)));
39
40    }
41}
Elías
10 Nov 2020
1public static int[] bucketSort(int[] a) {
2  Queue<Integer>[] buckets = fillBuckets(a);
3  int[] sorted = readBuckets(buckets);
4  return sorted;
5}
6
7public static Queue<Integer>[] fillBuckets(int[] array) {
8  if(array.length == 0){
9    Queue<Integer>[] r = new Queue[0];
10    return r;
11  }
12  int vmin = array[0];
13  int vmax = array[0];
14  for(int i = 0; i < array.length; i++){
15    if(array[i] > vmax){
16      vmax = array[i];
17    }
18    if(array[i] < vmin){
19      vmin = array[i];
20    }
21  }
22  Queue<Integer>[] buckets = new Queue[vmax - vmin + 1];
23  for(int i = 0; i < buckets.length; i++){
24    buckets[i] = new LinkedList<Integer>();
25  }
26  for(int i = 0; i < array.length; i++){
27    buckets[array[i] - vmin].add(array[i]);
28  }
29  return buckets;
30}
31
32public static int[] readBuckets(Queue<Integer>[] buckets) {
33  if(buckets.length == 0){
34    int[] e = new int[0];
35    return e;
36  }
37  ArrayList<Integer> a = new ArrayList<Integer>();
38  for(int i = 0 ; i < buckets.length; i++){
39    while(buckets[i].peek() != null){
40      a.add(buckets[i].remove());
41    }
42  }
43  int[] result = new int[a.size()];
44  for(int i = 0; i < a.size(); i++){
45    result[i] = a.get(i);
46  }
47  return result;
48}