排序算法

Posted myesn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了排序算法相关的知识,希望对你有一定的参考价值。

原理:

1 4    = 1
2 1 +1 = 2
3 2 +1 = 3
4 3 +1 = 4
5 5    = 5

prev: null
next: 1
newOrder 1 < originOrder 4
>0 && < 4


1 2 -1 = 1
2 3 -1 = 2
3 1    = 3
4 4    = 4
5 5    = 5

prev: 3
next: 4
newOrder 3 > originOrder 1
>1 && <4


1 1    = 1
2 3 -1 = 2
3 4 -1 = 3
4 5 -1 = 4
5 2    = 5

prev: 5
next: null
newOrder 5 > originOrder 2
>2 && <6


newOrder > originOrder,中间部分序号-1
newOrder < originOrder,中间部分序号+1

 

伪代码:

private async Task SortAsync(Guid id, int? toPreviousOrder, int? toNextOrder)
{
    var newOrder = GetNewOrder(toPreviousOrder, toNextOrder);
    var entity = await _store.FindAsync(id, required: true);
    if (entity.Order == newOrder)
        return;

    IEnumerable<Entity> entitiesBetween;
    if (newOrder > entity.Order)
    {
        entitiesBetween = await GetEntitiesAsync(x => x.Order > entity.Order && x.Order < newOrder + 1);
    }
    else
    {
        entitiesBetween = await GetEntitiesAsync(x => x.Order > newOrder - 1 && x.Order < entity.Order);
    }

    if (entitiesBetween.Any())
    {
        foreach (var entityBetween in entitiesBetween)
        {
            if (newOrder > entity.Order)
            {
                entityBetween.Order -= 1;
            }
            else
            {
                entityBetween.Order += 1;
            }
            
            entityBetween.WhenUpdated = DateTime.Now;
        }
        _store.UpdateRange(entitiesBetween);
    }

    entity.Order = newOrder;
    entity.WhenUpdated = DateTime.Now;
    _store.Update(entity);

    await _store.SaveChangesAsync();
}

private int GetNewOrder(int? toPreviousOrder, int? toNextOrder)
{
    if (toPreviousOrder.HasValue && toNextOrder.HasValue)
    {
        return toNextOrder.Value;
    }
    else if (toPreviousOrder.HasValue && !toNextOrder.HasValue)
    {
        return toPreviousOrder.Value;
    }
    else if (!toPreviousOrder.HasValue && toNextOrder.HasValue)
    {
        return toNextOrder.Value;
    }
    else throw new InvalidOperationException();
}

 

以上是关于排序算法的主要内容,如果未能解决你的问题,请参考以下文章

算法排序之堆排序

快速排序-递归实现

从搜索文档中查找最小片段的算法?

在第6731次释放指针后双重免费或损坏

TimSort算法分析

以下代码片段的算法复杂度