tags:

views:

98

answers:

2
+1  Q: 

Java BucketSort

I'm sure you probably get this a lot from CompSci students, I tried searching but mine looked a lot different from anything else I could find. Anyway, here is my class, it is supposed to sort an array of integers (then in the future be modified to sort objects, but ints will do for now).

My goal is to make an arrayList which is basically a row of buckets. then each bucket is a linked list. I feel like I'm on the right track, but the compiler doesn't like my last line of code, so I've run out of ideas.

here's an update. this is what I have now, but I still don't think it'll work

public void sorter(){
    int highest_int = 0;

    for(int i=0; i<entries.length; i++){
        if (highest_int < entries[i])
        highest_int = entries[i];
        }

ArrayList<LinkedList<Integer>> row = new ArrayList<LinkedList<Integer>>();  
LinkedList<Integer> column = new LinkedList<Integer>();

    while (highest_int>0){
        row.add(column);
        highest_int--;
    }   

    for(int i=0; i<entries.length; i++){
        int j = entries[i];
        column.add(0, j);
        row.set(j, column);
    }



}
A: 

The compiler "doesn't like" your code because the add() method of LinkedList doesn't return anything (has void return type). Therefore it cannot be used as an argument to the set() method. Basically, add() modified the object that it is called on, but doesn't return that object as a value.

The simplest change I can suggest that I think will make your code compile would be:

for(int i=0; i<entries.length; i++){
    int j = entries[i];
    column.add(0, j);
    row.set(j, column);
}

Beyond that, it's not clear to me what you are actually trying to accomplish here. I don't see anything that looks like a sort at all.

Dave Costa
I haven't got to the sorting part yet. I realized a mistake I made, I need to make as many buckets as the highest number in the array, not not the amount of objects. I'm making an arraylist populated with linkedlists. then another method will loop through the array and put the integers into the linkedlist that is in the bucket that matches the integer's value.
brant
A: 

The compile problem is that column.add() returns void.

A bigger problem is that the same LinkedList is used for each bucket. You need to create a new LinkedList in each iteration of one of the for loops.

UncleO
hm, how can I make it make a new linkedlist for each bucket?
brant
ArrayList<Bucket> buckets = new ArrayList<Bucket> where Bucket has within it a LinkedList<Integer> and the bucket number. Why a LinkedList, anyway?
Tony Ennis
it eventually needs to be able to handle objects? I'm no expert I just went with that? ha.
brant