快速排序导致堆栈溢出
我有以下代码(取自此处),但是当列表中有两个相同的值要排序时,它会导致 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该对 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!但不完整:选择第一个元素作为基准并且不首先对最小的子数组进行排序也会溢出堆栈。
But not complete: selecting the first element as pivot and not sorting the smallest subarray first will also overflow your stack.