So I’ve been trying to implement a quicksort myself, just to learn something from it, but it also generates a stackoverflowexception, but I can’t seem to find what the cause is.
Can someone give me a clue?
public void Partition(List<int> valuelist, out List<int> greater, out List<int> lesser)
{
lesser = new List<int>(); // <-- Stackoverflow exception here!
greater = new List<int>();
if (valuelist.Count <= 1)
return;
pivot = valuelist.First();
foreach (int Element in valuelist)
{
if (Element <= pivot)
lesser.Add(Element);
else
greater.Add(Element);
}
}
public List<int> DoQuickSort(List<int> list)
{
List<int> great;
List<int> less;
Partition(list, out great, out less);
DoQuickSort(great);
DoQuickSort(less);
list.Clear();
list = (List<int>)less.Concat(great);
return list;
}
You’re not putting any conditions on your recursive calls to
DoQuicksort, so it’ll never stop recursing, leading to a stack overflow. You should only be callingDoQuicksorton a list if it contains more than one element.Edit: As Will said in his comment, this is a very slow approach to “Quicksort”. You should look at in-place partitioning algorithms, as mentioned on Wikipedia’s Quicksort article.