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;






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


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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)