Skip to content

Instantly share code, notes, and snippets.

@tkokof
Created July 26, 2018 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkokof/848be24521be16e4bc6d7852d5e761a8 to your computer and use it in GitHub Desktop.
Save tkokof/848be24521be16e4bc6d7852d5e761a8 to your computer and use it in GitHub Desktop.
simple sorted list implementation using insert sort
// simple sorted list implementation using insert sort
// maintainer hugoyu
using System.Collections.Generic;
namespace Util
{
public class SortedList<T>
{
public SortedList(IComparer<T> comparer = null)
{
m_comparer = comparer;
}
public int Count
{
get
{
return m_elementList.Count;
}
}
public T this[int index]
{
get
{
return m_elementList[index];
}
}
public bool Contains(T item)
{
return m_elementList.BinarySearch(item, m_comparer) >= 0;
}
public void Add(T item)
{
var index = m_elementList.BinarySearch(item, m_comparer);
if (index < 0)
{
m_elementList.Insert(~index, item);
}
else
{
m_elementList.Insert(index, item);
}
}
public bool Remove(T item)
{
var index = m_elementList.BinarySearch(item, m_comparer);
if (index >= 0)
{
m_elementList.RemoveAt(index);
return true;
}
return false;
}
public void Clear()
{
m_elementList.Clear();
}
IComparer<T> m_comparer;
List<T> m_elementList = new List<T>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment