0

I'm trying to write a selection sort method for a LinkedHashMap/ArrayList but I'm having issues and I'm not sure what's wrong. It compiles but doesn't actually sort the list. I'm trying to sort in descending order by value. Any help would be appreciated.

public static List sort(LinkedHashMap<String, Integer> words) {


        List<Map.Entry<String, Integer>> entries = new ArrayList<>(words.size());
        entries.addAll(words.entrySet());

        int max;

        for(int i = 0; i < entries.size(); i++) {

            max = entries.get(i).getValue();

            for(int j = i + 1; j < entries.size(); j++) {

                if (entries.get(j).getValue().compareTo(entries.get(max).getValue()) > 0) {

                    max = entries.get(j).getValue();
                }

            }

            if(max != i) {

                Map.Entry temp1 = entries.get(i);

                entries.set(entries.get(i).getValue(), entries.get(max));

                entries.set(entries.get(max).getValue(), temp1);
            }

        }

        return entries;
    }
1
  • It seems that throughout this code, indices and values are used interchangeably, max is assigned to values but then compared to an index. Commented Sep 13, 2018 at 1:53

1 Answer 1

3

You're code is essentially correct, you've just mixed up values and indices in a few places.

You need to replace:

max = entries.get(i).getValue();

with

max = i;

This

max = entries.get(j).getValue();

with

max = j;

And

entries.set(entries.get(i).getValue(), entries.get(max));
entries.set(entries.get(max).getValue(), temp1);

with

entries.set(i, entries.get(max));
entries.set(max, temp1);

Make you sure you understand why the changes work.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure if that's all that is wrong. It puts the highest value one first, as it should, but the rest are still scrambled.
Yep, missed one. I've added it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.