import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
public class BucketSort {
public static void main(String[] args) {
float arr[] = { (float)0.897, (float)0.565,
(float)0.656, (float)0.1234,
(float)0.665, (float)0.3434 };
int size = arr.length;
System.out.println("printing the array");
printArray(arr);
bucketSort(arr,size);
System.out.println("printing the sorted array");
printArray(arr);
}
static void printArray(float arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
static void bucketSort(float [] arr, int size){
Vector<Float>[] buckets = new Vector[10];
for(int i = 0; i<10 ; i++){
buckets[i] = new Vector<Float>();
}
//segregating elements into buckets
for(int i=0;i<size;i++){
float idx = arr[i]*10;
System.out.println("((int)idx)-1>>"+(((int)idx))+", arr[i]"+arr[i]);
Vector vector = buckets[((int)idx)];
vector.add(new Float(arr[i]));
}
for(int i=0;i<10;i++){
Collections.sort(buckets[i]);
System.out.println("buckets[i]"+buckets[i]);
}
System.out.println("sorted buckets..");
int index=0;
for(int i=0;i<10;i++){
for(int j=0;j<buckets[i].size();j++){
arr[index]=buckets[i].get(j);
index++;
}
}
}
}
Output :
printing the array 0.897 0.565 0.656 0.1234 0.665 0.3434 ((int)idx)-1>>8, arr[i]0.897 ((int)idx)-1>>5, arr[i]0.565 ((int)idx)-1>>6, arr[i]0.656 ((int)idx)-1>>1, arr[i]0.1234 ((int)idx)-1>>6, arr[i]0.665 ((int)idx)-1>>3, arr[i]0.3434 buckets[i][] buckets[i][0.1234] buckets[i][] buckets[i][0.3434] buckets[i][] buckets[i][0.565] buckets[i][0.656, 0.665] buckets[i][] buckets[i][0.897] buckets[i][] sorted buckets.. printing the sorted array 0.1234 0.3434 0.565 0.656 0.665 0.897