sh********@gmail.com wrote:
Hi All,
I need a type where I can store my items in sorted order. And I want to
keep adding items to it, and want it to remain sorted. Is there any
type in .net which I can make use of.
I see there is SortedList<key, value> for hash tables, but could find
anything for a sorted list.
Currently I am using List<string> and whenever I add an item, I need to
call Sort() and it takes a long time - Order(nlogn). If the list is
already sorted, it will take just Order - logn. Does someone know if
there is a type where I can so such stuff.
Note that the List<T> class has a BinarySearch method that will return
a positive or zero index for the item if it already exists in the list
or the one's complement of the position where the item should be, if
it's not in the list yet.
The list must be sorted for the BinarySearch method to work, but it's
quite fast to locate the item's position.
Therefore, instead of simply adding to the list, which would ruin the
sort order and require you to perform a explicit sort afterwards, you
could add the item at its sorted position by using BinarySearch to find
it for you (warning: untested VB code ahead!):
Dim Index As Integer = List.BinarySearch(Item)
If Index < 0 then List.InsertAt(Index Xor -1, Item)
And your list would be kept sorted...
Regards,
Branco.