排序算法在处理较大的数据集时会导致堆栈溢出

本文关键字:栈溢出 堆栈 数据集 算法 处理 排序 | 更新日期: 2023-09-27 18:09:41

我正在寻找一种更好的方法来对以下类型的数据进行排序。下面的方法适用于较小的数据集(在某些系统上,在其他9000上为2000(,但是在处理较大的数据集时会导致堆栈溢出

保存数据的结构如下所示

public class AttributeItem
{
    public string AttributeType { get; set; }
    public string Title { get; set; }
    public string Value { get; set; }
    public int ObjectID { get; set; }
    public bool CanModify { get; set; }
    public bool CanDelete { get; set; }
    public bool? IsParent { get; set; }
    public int SortID { get; set; }
    public int? ParentSortID { get; set; }
    public bool Deleted { get; set; }
}
public class AttributeItemNode
{
    public AttributeItem Item {get;set;}
    public int Depth {get;set;}
    public AttributeItemNode(AttributeItem item , int Depth)
    {
        this.Item = item ;
        this.Depth = Depth;
    }
}

下面是需要将数据分类到单个对象中的示例,其中 int 表示其深度。子级别可能比示例数据中显示的三个级别更深

var items = new List<AttributeItem>();
items.Add(new AttributeItem{Title ="Parent1", ObjectID=1,SortID =1, IsParent= true, ParentSortID = Int32.MinValue});
items.Add(new AttributeItem{Title ="FooChild", ObjectID=2,SortID =2, IsParent= false, ParentSortID = 1});
items.Add(new AttributeItem{Title ="Parent2", ObjectID=4,SortID =4, IsParent= true, ParentSortID = Int32.MinValue});
items.Add(new AttributeItem{ Title ="Parent2Child1", ObjectID=5,SortID =5, IsParent= false, ParentSortID = 4});
items.Add(new AttributeItem{Title ="Parent2Child2", ObjectID=7,SortID =7, IsParent= false, ParentSortID = 4});
items.Add(new AttributeItem{Title ="Parent2Child2Child1", ObjectID=6,SortID =6, IsParent= false, ParentSortID = 5});

预期的输出如下(我已经从对象中删除了不相关的数据以帮助可读性(

Depth = 0 Title ="Parent1"
Depth = 1 Title ="FooChild" 
Depth = 0 Title ="Parent2"
Depth = 1 Title ="Parent2Child1" 
Depth = 2 Title ="Parent2Child2Child1"
Depth = 1 Title ="Parent2Child2"

这是实际的排序代码

    public static IList<AttributeItemNode> SortAttributeItems(IList<AttributeItem> list)
    {
        List<AttributeItemNode> newList = new List<AttributeItemNode>();
        SortAttributeItems(list, null, 0, newList);
        return newList;
    }
    private static void SortAttributeItems(IList<AttributeItem> list, AttributeItem currentItem, int depth, List<AttributeItemNode> newList)
    {
        AttributeItem newItem = null;
        // look for children
        if (currentItem != null)
        {
            foreach (AttributeItem item in list)
            {
                if (item.ParentSortID.HasValue && item.ParentSortID.Value != Int32.MinValue && item.ParentSortID.Value == currentItem.SortID)
                {
                    newList.Add(new AttributeItemNode(item, (depth + 1)));
                    SortAttributeItems(list, item, depth + 1, newList); 
                }
            }
        }
        if (depth == 0)
        {
            foreach (AttributeItem item in list)
            {
                if (!item.ParentSortID.HasValue || item.ParentSortID.Value == Int32.MinValue) 
                {
                    if (currentItem == null || item.SortID >= currentItem.SortID) 
                    {
                        if (newItem == null || newItem.SortID >= item.SortID)
                        {
                            newItem = item;
                        }
                    }
                }
            }
        }
        if (newItem != null)
        {
            newList.Add(new AttributeItemNode(newItem, depth));
            list.Remove(newItem);
            SortAttributeItems(list, newItem, depth, newList);
        }
    }

排序算法在处理较大的数据集时会导致堆栈溢出

这个问题

可以在不使用递归的情况下有效地解决。它可以分为两部分 - 创建一个树结构并使用迭代预序深度优先遍历来展平树,对每个级别进行排序。

对于第一部分,我们可以使用 LINQ ToLookup 方法在 O(N( 时间内ParentSortID来创建快速查找结构。

对于第二部分,遵循 DRY 原则,我将使用我的回答中的通用方法 如何通过 LINQ 展平树? 通过创建一个重载,该重载允许从项目和深度投影到自定义结果(如您所见,我已经有(:

public static class TreeUtils
{
    public static IEnumerable<TResult> Expand<T, TResult>(
        this IEnumerable<T> source, Func<T, IEnumerable<T>> elementSelector, Func<T, int, TResult> resultSelector)
    {
        var stack = new Stack<IEnumerator<T>>();
        var e = source.GetEnumerator();
        try
        {
            while (true)
            {
                while (e.MoveNext())
                {
                    var item = e.Current;
                    yield return resultSelector(item, stack.Count);
                    var elements = elementSelector(item);
                    if (elements == null) continue;
                    stack.Push(e);
                    e = elements.GetEnumerator();
                }
                if (stack.Count == 0) break;
                e.Dispose();
                e = stack.Pop();
            }
        }
        finally
        {
            e.Dispose();
            while (stack.Count != 0) stack.Pop().Dispose();
        }
    }
}

这是所讨论的方法的实现:

public static IList<AttributeItemNode> SortAttributeItems(IList<AttributeItem> list)
{
    var childrenMap = list.ToLookup(e => e.ParentSortID ?? int.MinValue);
    return childrenMap[int.MinValue].OrderBy(item => item.SortID)
        .Expand(parent => childrenMap[parent.SortID].OrderBy(item => item.SortID),
            (item, depth) => new AttributeItemNode(item, depth))
        .ToList();
}

有什么理由你不能简单地按照父指针来计算深度吗?

如果您将其放在以SortId为键的Dictionary<int,AttributeItem> map中,您现在可以获取每个AttributeItem item并执行以下操作:

int depth = 0;
var current = item;
while (!current.IsParent)
{ 
   depth++;
   current = map[current.ParentSortId;
}

如果对树或图形使用了众多 Nuget 包之一,则可以对数据执行此操作以及许多其他图形操作,包括检查它是否有效且不包含任何周期。

最好不要以两种方式表示相同的信息:您有IsParent,但您在ParentSortId上也有一个标记值。如果这些不一致怎么办?等。

public class AttributeItemNode : IComparable<AttributeNode> {
    public int CompareTo(AttributeItemNode other) {
        // compare the Ids in appropriate order
    }
}
public class NodeCollection {
    protected List<AttributeItemNode> nodes;
    public void AddNode() { }
    public void Sort() { 
       nodes.Sort();
       this.CalcDepth();
    }
    protected void CalcDepth {
        foreach (var node in nodes)
          if (node.IsParent) { node.Depth = 0; break; }
          //use the various Ids that are now in sorted order
          // and calculate the item's Depth.
    }
}

AttributeItem已经拥有排序所需的一切。使用IsParent(也许?(、SortIdParentSortId来实现上述CompareTo()

仅在排序后计算深度,这避免了递归的需要。

然后:

myNodeCollection.Sort()

List.Sort() .NET 智能地决定使用几种排序算法中的哪一种。