码迷,mamicode.com
首页 > 编程语言 > 详细

排序算法

时间:2019-11-07 12:48:23      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:new   datetime   div   中间   entity   enum   sync   origin   require   

原理:

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();
}

 

排序算法

标签:new   datetime   div   中间   entity   enum   sync   origin   require   

原文地址:https://www.cnblogs.com/myesn/p/sorting-algorithm.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!