I need a generic container that keeps its elements sorted and can be asked where (at which position) it would insert a new element, without actually inserting it.
Does such a container exist in the .NET libraries? The best illustration is an example (container sorts characters by ASCII value, let’s assume unicode does not exist):
sortedContainer.Add('d'); sortedContainer.Add('b'); sortedContainer.Add('g'); //container contains elements ordered like 'b' 'd' 'g' //index --------------------------------> 0 1 2 sortedContainer.GetSortedIndex('a'); //returns 0 sortedContainer.GetSortedIndex('b'); //returns 0 sortedContainer.GetSortedIndex('c'); //returns 1 sortedContainer.GetSortedIndex('d'); //returns 1 sortedContainer.GetSortedIndex('e'); //returns 2 sortedContainer.GetSortedIndex('f'); //returns 2 sortedContainer.GetSortedIndex('g'); //returns 2 sortedContainer.GetSortedIndex('h'); //returns 3 [...]
The search for the position should take advantage of the fact that the elements are sorted.
If you sort a
List<T>and then useList<T>.BinarySearchit will give you the index of the entry if it exists, or the bitwise complement of the index of where it would be inserted if you inserted then sorted. From that, you should easily be able to build your method.Sample code matching your example, but not the results – if you look at your sample, you’ve only got 3 entries, so it doesn’t make sense for ‘h’ to return 4 or ‘g’ to return 3. I hope that’s your example which is slightly off, rather than me misunderstanding the problem 🙂 Note that the sorting isn’t automatic – you’d have to sort the list explicitly before calling GetSortedIndex.