1

I'm trying to solve a problem in which it would be useful to have a data structure like

var list = new SortedList<int>(); 
list.Add(3); // list = { 3 } 
list.Add(1); // list = { 1, 3 }
list.Add(2); // list = { 1, 2, 3 }
int median = list[list.Length / 2];

i.e.

  • O(n) insertion
  • O(1) lookup by index

but I can't see that such a thing exists? I see that there's some confusing SortedList<T,U> and then an interface SortedList, but neither of those are what I'm looking for.

user7127000
  • 3,143
  • 6
  • 24
  • 41

1 Answers1

0

The sorted list in the .NET framework is an associative list (that is it is for key/value pairs). You can use a regular List<T> if you use its binary search functionality, which works if you keep the list sorted at all times. You can encapsulate it in an extension method:

static class SortedListExtensions {
    public static void SortedAdd<T>(this List<T> list, T value) {
        int insertIndex = list.BinarySearch(value);
        if (value < 0) {
            value = ~value;
        }
        list.Insert(insertIndex, value);
    }

    //Added bonus: a faster Contains method
    public static bool SortedContains<T>(this List<T> list, T value) {
        return list.BinarySearch(value) >= 0;
    }
}


List<int> values = new List<int>();
values.SortedAdd(3);
values.SortedAdd(1);
values.SortedAdd(2);
Sefe
  • 13,731
  • 5
  • 42
  • 55