【问题标题】:Sorting algorithm causes stack overflow when processing larger data-sets?处理较大数据集时排序算法会导致堆栈溢出?
【发布时间】:2016-10-01 02:03:17
【问题描述】:

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

保存数据的结构如下所示

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

    }

【问题讨论】:

  • 我明白你的意思,但正如问题中所述。它因大量数据而失败。因此,除了寻找优化之外,还有更多。如果它只是在使用更大的数据集时运行速度真的很慢,那么我会同意。
  • 然后编辑你的标题以要求改进以外的其他内容,这意味着做一些更好的工作,以及你的第一段,询问关于让它更好,这也说它有效,但我想改进它
  • 谢谢。我的近距离投票已被撤回。 :-)
  • 正如我所见,depth 也是根据可用的层次结构/数据进行计算的,默认情况下不提供
  • 请说明(接近文章开头)为什么您使用自己的排序程序而不是使用现有的排序程序。

标签: c# .net algorithm


【解决方案1】:

使用递归可以有效地解决问题。它可以分为两部分 - 创建一个树结构并使用迭代 pre-order Depth First Traversal 将树展平,对每个级别进行排序。

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

对于第二部分,遵循DRY 原则,我将使用我对How to flatten tree via 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();
}

【讨论】:

  • 一个疑问,在Expand 方法调用中,您提供resultSelector 如下(item, depth) =&gt; new AttributeItemNode(item, depth),深度值来自哪里,因为这是&lt;AttributeItemNode 的一部分而不是@987654333 @
  • @MrinalKamboj 它来自Expand 方法(类似于您的递归方法中的depth 变量)。由于我在内部使用了明确的stack,因此stack.Count 是当前深度。
  • 一旦我更改了 items.ToLookup(e => e.ParentSortID ?? int.MinValue); to list.ToLookup(e => e.ParentSortID ?? int.MinValue);
【解决方案2】:

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

如果你把它放在Dictionary&lt;int,AttributeItem&gt; map 中,并以SortId 作为键,你现在可以使用每个AttributeItem item 并执行以下操作:

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

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

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

【讨论】:

  • 您可以通过遍历Parent 为子级分配深度,但仍需要递归才能按预期创建层次结构。事实上,我提供的解决方案使用了类似的基于字典的策略
【解决方案3】:
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 智能地决定使用几种排序算法中的哪一种。

【讨论】:

  • 这肯定不能解决 OP 的要求,在 AttributeItem List 中将孩子与父母联系起来的第一部分尚未完成,然后 OP 要求将项目列在特定的子层次结构中,而不是通用排序顺序,这是您的解决方案将使用 IComparable&lt;AttributeNode&gt; 实现的,因为它不能为每个子部分执行此操作
  • 问题是关于避免递归引起的堆栈溢出和计算深度。只需要按键顺序即可。如果需要某种树或链表,则只需遍历排序列表并构建它。即使这样,也避免了递归。那么,此解决方案有可能处理大量数据。
  • 请尝试根据您的建议实施解决方案,您将了解它无法按预期工作的地方,请尝试OP提供的数据。 ParentsChildren 的排列使用IComparer 进行排序,过于简化问题,它不会导致预期的树结构
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 2016-02-09
  • 2015-05-21
相关资源
最近更新 更多