diff --git a/src/client/spark_core/Collections/SortedList.cs b/src/client/spark_core/Collections/SortedList.cs new file mode 100644 index 000000000..1a008c1d4 --- /dev/null +++ b/src/client/spark_core/Collections/SortedList.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace bts.collections { + public class SortedList : IEnumerable { + T[] _values; + int _size = 0; + readonly IComparer _comparer; + + public SortedList(IComparer comparer) { + _values = new T[4]; + _size = 0; + } + public SortedList(IEnumerable items, IComparer comparer) { + var capacity = items.Count(); + _values = new T[_size]; + foreach (var item in items) { + Add(item); + } + } + + bool Contains(T item) { + return BinarySearch(item) >= 0; + } + + public void Add(T item) { + var capacity = _values.Length; + // Check if item is already in array + int pos = BinarySearch(item); + if (pos >= 0) throw new ArgumentException($"SortedList already contains {item}"); + // If not check if we need to expand + if (capacity+1 >= _size) { + Expand(); + } + // Shift items above position up 1 + pos = ~pos; + Array.Copy(_values, pos, _values, pos + 1, _size - pos); + // Put new value in the hole left + _values[pos] = item; + } + public bool Remove(T item) { + int index = BinarySearch(item); + if (index >= 0 && index <= _size) { + _size--; + Array.Copy(_values, index + 1, _values, index, _size - index); + _values[_size] = default(T); + return true; + } + return false; + } + + #region Private + private void Expand() { + // double size of array + T[] expanded = new T[_size * 2]; + Array.Copy(_values, expanded, _size); + _values = expanded; + } + + int BinarySearch(T item) { + return Array.BinarySearch(_values, 0, _size, item, _comparer); + } + + #endregion + + + #region IEnumerable + + public IEnumerator GetEnumerator() { + for (int x = 0; x < _size; ++x) { + yield return _values[x]; + } + } + + IEnumerator IEnumerable.GetEnumerator() { + return GetEnumerator(); + } + #endregion + } +}