-2

I'm trying to sort Dictionary using buble sort. The problem i have is that i want to keep keys. For example:

I have dictionary looks like this:

{[0,5],[1,2],[2,3],[3,1],[4,9]}

After using Bubble Sort on it i should have Dictionary like this:

{[3,1],[1,2],[2,3],[0,5],[4,9]}

Is that even possible ?

infexo37
  • 13
  • 3
  • do u want sort or trying to implement buble sort for dictionaries? – Mustafa ASAN Dec 04 '15 at 09:31
  • I'm trying to implement buble sort for dictionaries. But after sorting keys are not kept. – infexo37 Dec 04 '15 at 09:33
  • Something like this. I have to prove that i can write BubbleSort for Dictionaries if i want to use LINQ in future projects. – infexo37 Dec 04 '15 at 09:38
  • I am still unclear as to whether your intention is to write a sort program (in which case why specifically bubble sort?) or to end up with a sorted dictionary. My answer to you will be different depending on that. – ClickRick Dec 04 '15 at 09:55
  • As Oliver mentioned in his answer, Dictionaries are not ordered data structures. What you want to achieve is unclear. – Saverio Terracciano Dec 04 '15 at 10:03

1 Answers1

1

Dictionaries have no notion of order (cf. The order of elements in Dictionary), thus they cannot be sorted themselves. The two dictionaries you gave would be equivalent.

You could instead create a List of key-value pairs and implement your BubbleSort to compare only the second element of each pair. Like this, but using Bubblesort instead of OrderBy:

var sample = new Dictionary<int, int>
{
    {0,5},
    {1,2},
    {2,3},
    {3,1},
    {4,9}
};

var keyValuePairs = sample.Select(p => new Tuple<int, int>(p.Key, p.Value)).ToList();

var sortedKeyValuePairs = keyValuePairs.OrderBy(t => t.Item2);
Community
  • 1
  • 1
Oliver
  • 351
  • 2
  • 6