快速排序导致堆栈溢出

发布于 2024-08-18 08:21:00 字数 584 浏览 6 评论 0原文

我有以下代码(取自此处),但是当列表中有两个相同的值要排序时,它会导致 stackoverflow 异常。

有人可以帮我看看这是什么原因造成的吗?

 public static IEnumerable<int> QSLinq(IEnumerable<int> _items)
{
    if (_items.Count() <= 1)
        return _items;

    var _pivot = _items.First();

    var _less = from _item in _items where _item < _pivot select _item;
    var _same = from _item in _items where _item == _pivot select _item;
    var _greater = from _item in _items where _item > _pivot select _item;

    return QSLinq(_less).Concat(QSLinq(_same)).Concat(QSLinq(_greater));
}

I have the following code, (taken from here), but it causes a stackoverflow exception when there's two the same value's in the list to sort.

Can someone help me what's causing this?

 public static IEnumerable<int> QSLinq(IEnumerable<int> _items)
{
    if (_items.Count() <= 1)
        return _items;

    var _pivot = _items.First();

    var _less = from _item in _items where _item < _pivot select _item;
    var _same = from _item in _items where _item == _pivot select _item;
    var _greater = from _item in _items where _item > _pivot select _item;

    return QSLinq(_less).Concat(QSLinq(_same)).Concat(QSLinq(_greater));
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撩动你心 2024-08-25 08:21:00

您不应该对 sort _same 进行递归调用 - 您知道它已排序,因为所有值都是相同的!

You shouldn't be making a recursive call to sort _same - you know it's sorted, since all the values are the same!

挥剑断情 2024-08-25 08:21:00

但不完整:选择第一个元素作为基准并且不首先对最小的子数组进行排序也会溢出堆栈。

But not complete: selecting the first element as pivot and not sorting the smallest subarray first will also overflow your stack.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文