Sorting Java.

Started by
2 comments, last by Wooh 9 years, 10 months ago

Question guys, need some help about sorting using arraylist, i don't know why it doesn't sort at all.. >_< sorry for the post.

public class Driver2 {

static Random r = new Random();

public static void main(String[]args) {

ArrayList<Integer> list = new ArrayList<Integer>();

for(int i = 0 ; i < 3 ; i++) {
list.add(rollDice());
}

for(Integer g : list)
System.out.println(g);

for(int index = 0 ; index < list.size() ; index++) {
for(int i = 1 ; i < list.size() - 1 ; i++) {

if(list.get(index) < list.get(i)) {
int temp = list.get(index);
list.remove(index);
list.add(index , list.get(i));
list.remove(i);
list.add(i, temp);
}
}
}

for(Integer g : list)
System.out.println(g);

}

public static int rollDice() {

int temp;
temp = (1 + r.nextInt(6));

return temp;
}
}

Advertisement
First, what does "it doesn't sort at all" even mean? Is there no change? Is there change but it's not the expected result? Sample output might help.

Then, what algorithm are you trying to implement? I don't recognize it (possibly because of the horrible code formatting) and the quadratic runtime does not look like something often-used. Is that a well-known algorithm or something you think 'should work'. If the latter, have you tried to test it on paper if it should work at all.
I would also think it's highly unlikely you really want to use ArrayList.add() and ArrayList.remove() while sorting. It is unnecessary (in general you want to swap elements) and will cause hell with indices.
Also note, if implementing the sorting algorithm is not the purpose of this, there are sorting functions in java.util.Arrays.

If this is not homework, then use the standard sort of java (eg Collections.sort).

If this is homework, and your task is to write bubblesort,then take a closer look here:


        for(int index = 0 ; index < list.size() ; index++) {
            for(int i = 1 ; i < list.size() - 1 ; i++) {

The swap code also doesn't work. Take a look at these lines:
list.remove(index);
list.add(index , list.get(i));
Remove will shift all elements after the remove element so that they are stored at an index that is one smaller. If i > index then list.get(i) will not give you the same number as it did before you called remove.

This topic is closed to new replies.

Advertisement