Search code examples
javasortingdictionaryhashmapselection-sort

How to sort a LinkedHashMap by value without Collections.sort()?


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;
    }

Solution

  • 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.