开发者

Quicksort causes stackoverflow

开发者 https://www.devze.com 2022-12-17 08:08 出处:网络
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.

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 _开发者_如何学Goitem in _items where _item > _pivot select _item;

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消