0

I am new to java and am attempting to make a bubble sort work for a double. For some reason sorting is a real hangup for me. Below is the code, but it isn't doing anything. It doesn't error out, but it also doesn't sort. I feel like it is a stupid syntax mistake. My goal is to get the value of an item in my item file to sort descending.

public static ArrayList<Item> sortValue(ArrayList<Item> example)
    {
        for (int i = 0; i < example.size() - 1; i++ )
            for (int j = 0; j < example.size() - 1 - i; j++)
                if (example.get(j).getValue() == (example.get(j+1).getValue())) {
                    example.add(j+1, example.remove(j));
                }

        return example;
    }

I call the method at the beginning of another method:

sortValue(example);

And still get the below result:

books   2.0 2.0 2   2
shoes   1.0 1.0 1   1
sword   10.0    10.0    10  10

Not pretty but basically the 10's should be at the top. Appreciate suggestions!

JenInCode
  • 250
  • 2
  • 8
  • 2
    Well, your code only does anything if the value at the current index is equal to the value at the immediately adjacent index. And what it does then looks incorrect as well. – Elliott Frisch Apr 20 '18 at 13:29
  • Why are you using `==` to compare? Shouldn't it be `<=` or `>=`? Furthermore, the comparison based on `==` will check if it is the same instance, not necessarily if the objects are semantically equal (https://stackoverflow.com/questions/7520432/what-is-the-difference-between-vs-equals-in-java) – Abaddon666 Apr 20 '18 at 13:29

1 Answers1

1

What you are trying to do is called BubbleSort, but you are missing some things:

public static ArrayList<Item> sortValue(ArrayList<Item> example) {
    Item aux = null;
    for(int i = 0; i < example.size(); i++){
        for(int j = 0; j < example.size() - 1; j++){
            if(example.get(j).getValue() > example.get(j + 1).getValue()){
                aux = example.get(j);
                example.set(j, example.get(j + 1));
                example.set(j + 1, aux);
            }
        }
    }
    return example;
}

Notice that we used a local variable called aux to store the list j position and then update it to the j + 1 value. Also notice that we are using the > (greater than) comparator instead of ==.

Glim
  • 361
  • 1
  • 10
  • Thanks. This is helpful, though it does argue with me on lines 7 that j cannot be converted to a double and line 8 that no suitable method for set(int, double) – JenInCode Apr 20 '18 at 13:54
  • and `j` is the position of the array (type `Integer`)... it is not an `double` value... try it with this changes. – Glim Apr 20 '18 at 14:01
  • yes!!! thanks! i appreciate the explanation as well and have a better understanding now. – JenInCode Apr 20 '18 at 14:10