说明:采用和Redis排序算法类似的跳表,支持大量数据的实时排序。
public class SkipListLevelInfo<T> where T : class
{
public SkipListNode<T> Next;
public uint Span;
}
public class SkipListNode<T> where T : class
{
public T Item { get; private set; }
//level为0那一层的前面节点
public SkipListNode<T> Prev;
//根据Level记录每一层的下一个节点以及中间间隔的距离
public SkipListLevelInfo<T>[] LevelsInfo { get; private set; }
public SkipListNode(T obj, uint level)
{
this.Item = obj;
this.LevelsInfo = new SkipListLevelInfo<T>[level];
for(int i=0;i<level; i++)
{
this.LevelsInfo[i] = new SkipListLevelInfo<T>();
}
}
}
/// <summary>
/// 跳表,仿照redis的实现
/// 从小到大排,返回1,表示要交换,-1,表示不要交换,0表示是同一个元素
/// 注意不同元素不能返回0
/// Debug模式下,1000000次add 花费6.5s
/// 简单的原理图如下
/// level 3 || 8------------------------------>1 0
/// level 2 || 2------>2------>4-------------->1 0
/// level 1 || 2------>2------>2------>2------>1 0
/// level 0 || 1-->1-->1-->1-->1-->1-->1-->1-->1 0
/// value X 1 3 4 6 8 10 15 18 20
/// node H N1 N2 N3 N4 N5 N6 N7 N8 N9
/// </summary>
/// <typeparam name="T"></typeparam>
public class SkipList<T> where T : class
{
private Random random;
private SkipListNode<T> header;
private SkipListNode<T> tail;
private uint currentLevel;
private uint maxLevel;
private Comparison<T> comparison;
public uint Count { get; private set; }
/// <summary>
/// </summary>
public SkipList(Comparison<T> comparison, uint maxLevel = 32)
{
this.comparison = comparison;
random = new Random((int)(DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalSeconds);
this.maxLevel = maxLevel;
currentLevel = 1;
Count = 0;
header = new