实时排序算法(跳表)

本文介绍了使用Redis中类似跳表的数据结构,来支持大量数据的高效实时排序,适用于构建排行榜等场景。
摘要由CSDN通过智能技术生成

说明:采用和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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值