Add SortedList class.

This commit is contained in:
Eric Harding committed 2018-03-09 15:52:36 -05:00
1 parent d48584fffe
commit 0754fc7947
1 file changed
+83
@@ -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<T> : IEnumerable<T> {
T[] _values;
int _size = 0;
readonly IComparer<T> _comparer;
public SortedList(IComparer<T> comparer) {
_values = new T[4];
_size = 0;
}
public SortedList(IEnumerable<T> items, IComparer<T> 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<T>(_values, 0, _size, item, _comparer);
}
#endregion
#region IEnumerable
public IEnumerator<T> GetEnumerator() {
for (int x = 0; x < _size; ++x) {
yield return _values[x];
}
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
#endregion
}
}