How to sort a LinkedHashMap by value without Collections.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;
max
1 Answer
1
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.
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.
– Taylor Swift
Sep 13 '18 at 2:54
Yep, missed one. I've added it now.
– SirRaffleBuffle
Sep 13 '18 at 3:42
worked great thank you!
– Taylor Swift
Sep 13 '18 at 4:01
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
It seems that throughout this code, indices and values are used interchangeably,
max
is assigned to values but then compared to an index.– khachik
Sep 13 '18 at 1:53