Reputation: 295
In my program, I will be receiving tuples of data: (Value, Order)
. I want to sort all the tuples by ascending Order
in a list or dictionary. I get the tuples one by one in a while loop.
What would be the most efficient way of sorting the tuples? I have thought about sorting the tuples as I receive them one by one, then inserting them into the list or dictionary; or I could gather all of the tuples in one list or dictionary first, then sort them. Which of these methods would be best?
Also, I'm not sure whether a list or dictionary would be best for storing this information, or if there is even a significant difference between using either one.
Edit: I should note that after sorting, I need to produce a string of all the Value
s.
Upvotes: 0
Views: 50
Reputation: 16878
You can be interested in the SortedDictionary
class:
SortedDictionary<string, string> dict =
new SortedDictionary<string, string>();
As MSDN says:
SortedDictionary has (...) insertion and removal operations for unsorted data: O(log n)
So it will be faster than adding all tuples and then sorting them with O(n log n) complexity.
Upvotes: 1
Reputation: 1262
You can use SortedList or SortedDictionary. The difference is explained here.
The SortedDictionary generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this respect, it is similar to the SortedList generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:
• SortedList uses less memory than SortedDictionary.
• SortedDictionary has faster insertion and removal operations for unsorted data: O(log n) as opposed to O(n) for SortedList.
• If the list is populated all at once from sorted data, SortedList is faster than SortedDictionary.
Each key/value pair can be retrieved as a KeyValuePair structure, or as a DictionaryEntry through the nongeneric IDictionary interface.
Keys must be immutable as long as they are used as keys in the SortedDictionary. Every key in a SortedDictionary must be unique. A key cannot be null, but a value can be, if the value type TValue is a reference type.
SortedDictionary requires a comparer implementation to perform key comparisons. You can specify an implementation of the IComparer generic interface by using a constructor that accepts a comparer parameter; if you do not specify an implementation, the default generic comparer Comparer.Default is used. If type TKey implements the System.IComparable generic interface, the default comparer uses that implementation.
Upvotes: 0
Reputation: 1545
You can use SortedDictionary, and it will do the work most probably faster than you. The type of data structure depends on how are you going to access or query the data
Upvotes: 0