I am working on an assignment where we need to take a integer array and sort it using a Bucket Sort.
My issue comes when trying to increase to the next column, but only if there is an element already in the "bucket" already.
So, using my array below, 22 is the first element and will go in row 2 column 0, which is correct, but using i as the column is obviously not correct because it always increases the column and I eventually get an index out of bounds.
I can't wrap my head around how to correctly increase the index of the bucketArray column, only if there is an element in that position. I've tried using an additional for loop that handled the column but that didn't work either.
Any pointers in the right direction would be greatly appreciated! I'm sure also there are other ways to create a bucket sort but the assignment said to use a 2d array for each bucket so I was trying to get it to work that way.
public class BucketSort {
public static void main(String args[]) {
int intArray[] = {22, 45, 12, 8, 10, 6, 72, 81, 33, 18, 50, 14};
int eachBucket[][] = new int[10][11];
int j;
double max = 81;
int min = 6;
int divider = (int)Math.ceil((max + 1) / 10);
for(int i = 0; i < intArray.length; i++) {
j = (int)Math.floor(intArray[i] / divider);
eachBucket[j][i] = intArray[i];
}
}
}
Use the 11th element to track how many elements in the current bucket have been used, something like this
for(int i = 0; i < intArray.length; i++) {
j = (int)Math.floor(intArray[i] / divider);
eachBucket[j][eachBucket[j][10]] = intArray[i];
eachBucket[j][10]++;
}
The problem with a fixed-sized second dimension is if you have more that n elements to put into any one bucket. Probably not a problem here.