I am trying to write code for bucket sort, but am confused in bucket size of each bucket. My code is below. input array: {12, 11, 13, 5, 6, 7,10,22,4,16,1,26};
I am passing bucket size of each bucket >3 then I dont get the output in sorted order. It gives perfect ans for bucket size 1 and 2
public void bucsort(int[] arr,int bucketSize){
if(arr.length==0) return;
int max=arr[0];
int min=arr[0];
for(int i=0; i<arr.length;i++){
if(arr[i]<min)
{
min=arr[i];
}
else
max=arr[i];
}
int bucketCount= (max - min) / bucketSize + 1;
List<List<Integer>> buckets = new ArrayList<List<Integer>>(bucketCount);
// int divider= (max+1)/bucketCount;
for (int i = 0; i < bucketCount; i++) {
buckets.add(new ArrayList<Integer>());
}
for (int i = 0; i < arr.length; i++) {
buckets.get((arr[i]-min) / bucketSize).add(arr[i]);
}
int currentIndex = 0;
for (int i = 0; i < buckets.size(); i++) {
Integer[] bucketArray = new Integer[buckets.get(i).size()];
bucketArray = buckets.get(i).toArray(bucketArray);
InsertionSort(bucketArray);
for (int j = 0; j < bucketArray.length; j++) {
arr[currentIndex++] = bucketArray[j];
}
}
}
Is there any relation between no. of buckets and its size ?
I edited my method for max-min function and also debugged the program. There seems to be some mistake in my insertion sort
the code is:
public void InsertionSort(Integer[] arr){
for(int i=1; i<arr.length; i++){
int value=arr[i];
int hole=i;
while(hole>0 && arr[hole-1]>value){
arr[hole]=arr[hole-1];
hole--;
}
arr[hole-1]=value;
}
}
main func
public static void main(String[] args) {
int arr[] = {12, 11, 13, 5, 6, 7,10,22,4,16,1,26};
BucketSort ob = new BucketSort();
ob.bucsort(arr, 5);
printArray(arr);
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
My output for bucket size 5 : 5 1 4 6 7 10 12 11 13 16 22 26 for size 3: 1 5 4 6 7 12 10 11 13 16 22 26 for size 2: 1 4 5 6 7 10 12 11 13 16 22 26
InsertionSortmethod? We can help you better if you post complete code and complete output with different bucket sizes in your question (say, size 2 and size 4).