HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Always sorted list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortedlistalways

Problem

In this list, each newly inserted element is put in its place in order using IComparer. The implementation uses a LinkedList for the increased performance of insertion. Are there any problems with this object?

public class SortedCollection : ICollection
{
    private readonly LinkedList _sortedList;
    private readonly IComparer _comparer;

    public SortedCollection(IComparer comparer)
    {
       if (comparer == null) throw new ArgumentNullException("comparer");

       _comparer = comparer;
       _sortedList = new LinkedList();
    }

    public SortedCollection()
       : this(Comparer.Default)
    { }

    public void Add(T item)
    {
       LinkedListNode node = _sortedList.First;
       if (node == null || _comparer.Compare(node.Value, item) > 0)
       {
          _sortedList.AddFirst(item);
       }
       else
       {
          while (node != null && _comparer.Compare(node.Value, item)  GetEnumerator()
    {
       return _sortedList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
       return _sortedList.GetEnumerator();
    }

    public void Clear()
    {
       _sortedList.Clear();
    }

    public bool Contains(T item)
    {
       return _sortedList.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
       _sortedList.CopyTo(array, arrayIndex);
    }

    public int Count
    {
       get { return _sortedList.Count; }
    }

    public bool IsReadOnly { get { return false; } }
}

Solution

Though insertion itself is efficient, finding the right index is not with this implementation. You are still doing a linear search. For insertion, a sorted tree is more efficient, and that, too, could be iterated over in sort order. I don't know why you chose a list in the first place, but typically the reason for that is accessing elements by index. That is not possible efficiently with a tree, but with a linked list it's not either.

To cut a long story short, you need to know what operations need to be fast to pick the right data structure, but a tree seems more appropriate than your linked list approach when it comes to insertion which is what you mentioned in your question.

Context

StackExchange Code Review Q#63888, answer score: 13

Revisions (0)

No revisions yet.