Question

27527-683
27525-1179
27525-1571
27525-1813
27525-4911
27526-1303
27526-3641
27525-3989
27525-4083
27525-4670
27526-4102
27526-558
27527-2411
27527-4342

this is the list of key where it is declared as string in a map
then i want to sort it in ascending order.
how can i use a bubble sorting method inside a map?
where the value of the key is a list. in order to get :

27525-1179
27525-1571
27525-1813
27525-3989
27525-4083
27525-4670
27525-4911
27526-558
27526-1303
27526-3641
27526-4102
27527-683
27527-2411
27527-4342

Was it helpful?

Solution

You should be able to just perform an in-order traversal on your tree. Bu if you insist here is what you would do.

keyList = yourTreeMap.getKeys();
for(i = keyList.length-1; i > 0; i--)
    for(j = 0; j < i; j++)
       if (keyList[j] > keyList[j+1]) keyList.swap(j, j+1);

Since you don't specify a lnaguage, I present psuedocode.

OTHER TIPS

In general you just use the same bubble sort algorithm as normal it's just your comparison condition that's tweaked here to look at both the key and the value to determine what is greater than what, that is compare the keys first and if they're equal then compare the values if the keys don't match then use the difference in the values to get your result of swap or don't swap. Bubble sort is bad efficiency-wise though if you're using this in a real world scenario.

Jon got the post in before me but basically what he wrote looks right except you'd want a complex condition for the if within the nested loop, like

if(key1<key2)
    keyList.swap(i,j)
else if(keyList[key1]<keyList[key2])
    keyList.swap(i,j)

of course as he also stated how these keys/values are actually extracted/used will depend on the language, which is lacking in the question or tags.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top