bucket sort in java code example
Example 1: bucket sort java
public class Main
{
public static int[] bucket_sort(int[] arr, int max_value)
{
int[] bucket = new int[max_value + 1];
int[] sorted_arr = new int[arr.length];
for (int i= 0; i <arr.length; i++)
bucket[arr[i]]++;
int pos = 0;
for (int i = 0; i < bucket.length; i++)
for (int j = 0; j < bucket[i]; j++)
sorted_arr[pos++] = i;
return sorted_arr;
}
static int maxValue(int[] arr)
{
int max_value = 0;
for (int i = 0; i < arr.length; i++)
if (arr[i] > max_value)
max_value = arr[i];
return max_value;
}
public static void main(String args[])
{
int[] arr ={80, 50, 30, 10, 90, 60, 0, 70, 40, 20, 50};
int max_value = maxValue(arr);
System.out.print("\nOriginal : ");
System.out.println(Arrays.toString(arr));
System.out.print("\nSorted : ");
System.out.println(Arrays.toString(bucket_sort(arr,max_value)));
}
}
Example 2: java bucket sort
public static int[] bucketSort(int[] a) {
Queue<Integer>[] buckets = fillBuckets(a);
int[] sorted = readBuckets(buckets);
return sorted;
}
public static Queue<Integer>[] fillBuckets(int[] array) {
if(array.length == 0){
Queue<Integer>[] r = new Queue[0];
return r;
}
int vmin = array[0];
int vmax = array[0];
for(int i = 0; i < array.length; i++){
if(array[i] > vmax){
vmax = array[i];
}
if(array[i] < vmin){
vmin = array[i];
}
}
Queue<Integer>[] buckets = new Queue[vmax - vmin + 1];
for(int i = 0; i < buckets.length; i++){
buckets[i] = new LinkedList<Integer>();
}
for(int i = 0; i < array.length; i++){
buckets[array[i] - vmin].add(array[i]);
}
return buckets;
}
public static int[] readBuckets(Queue<Integer>[] buckets) {
if(buckets.length == 0){
int[] e = new int[0];
return e;
}
ArrayList<Integer> a = new ArrayList<Integer>();
for(int i = 0 ; i < buckets.length; i++){
while(buckets[i].peek() != null){
a.add(buckets[i].remove());
}
}
int[] result = new int[a.size()];
for(int i = 0; i < a.size(); i++){
result[i] = a.get(i);
}
return result;
}
Example 3: bucket sort algorithm java
import java.util.ArrayList;
import java.util.Collections;
public class BucketSort {
public void bucketSort(float[] arr, int n) {
if (n <= 0)
return;
@SuppressWarnings("unchecked")
ArrayList<Float>[] bucket = new ArrayList[n];
for (int i = 0; i < n; i++)
bucket[i] = new ArrayList<Float>();
for (int i = 0; i < n; i++) {
int bucketIndex = (int) arr[i] * n;
bucket[bucketIndex].add(arr[i]);
}
for (int i = 0; i < n; i++) {
Collections.sort((bucket[i]));
}
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0, size = bucket[i].size(); j < size; j++) {
arr[index++] = bucket[i].get(j);
}
}
}
public static void main(String[] args) {
BucketSort b = new BucketSort();
float[] arr = { (float) 0.42, (float) 0.32, (float) 0.33, (float) 0.52, (float) 0.37, (float) 0.47,
(float) 0.51 };
b.bucketSort(arr, 7);
for (float i : arr)
System.out.print(i + " ");
}
}