Search code examples
c#.net-4.0sortedset

How to efficiently search a sortedset with an inequality?


Ok say I have a strongly typed SortedSet of type int. I want to find the largest number in the set that is less than x.

Maybe this is the wrong data structure for this but my intuitive thinking is that I have a sorted collection. Surely it makes sense that I should be able to do this type of search via the .NET framework?


Solution

  • Since SortedSet does not provide direct access by index you have to rely on enumeration (linear search - O(n)). One possibly better method is to use SortedSet.GetViewBetween and Last, but it does not look like you can get last element without enumerating all elements in view anyway.

    Collection with direct access by index (i.e. List) would let you do binary search with O(lg n) performance - so if you need to search a lot copying to list could with ToList give better overall performance when using List.BinarySearch (which give you position of next element to one you are looking for).

    // starting sample for BinarySearch approach  
    // not handling case where item not in the list (x = 1).
    // List have to be sorted which is the case starting from sorted set: sortedSet.ToList()
    var list = new List<int>{ 1,3, 5, 7, 8,9}; 
    var index = list.BinarySearch(8);
    Console.WriteLine(index < 0 ? list[~index - 1] : list[index-1]);