Click here to Skip to main content
15,920,217 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi! I keep getting StackOverFlowException in my code and I can't seem to find the problem. Please help me.
C#
class Program
{
    static void Main(string[] args)
    {
        int x = 3;
        List<int> num = new List<int>();
        Random rnd = new Random();
        for (int i = 0; i < x; i++)
        {
            num.Add(rnd.Next(99));
        }
        Sort s = new Sort();
        int q = 1, w = 0;

        s.QuickSort<int>(num);


    }
}

public class Sort
{
    public Sort()
    {
    }
    public void QuickSort<T>(List<T> Tlist) where T : IComparable
    {
        List<T> tmp = QuickSortHelper(Tlist);
        Tlist.Clear();
        foreach (T t in tmp)
            Tlist.Add(t);
    }
    public List<T> QuickSortHelper<T>(List<T> Tlist)  where T : IComparable
    {
        List<T> left= new List<T>(), right = new List<T>(), returList = new List<T>();
        if (Tlist.Count <= 1)
            return Tlist;
        int x =Tlist.Count-1;
        T pivot = Tlist[x];
        foreach (T t in Tlist)
            if (t.CompareTo(pivot) == -1)
                left.Add(t);
            else right.Add(t);
        foreach(T t in QuickSortHelper<T>(left))
            returList.Add(t);
        returList.Add(pivot);
        foreach (T t in QuickSortHelper<T>(right))
            returList.Add(t);
        return returList;
    }
Posted
Updated 5-Sep-10 6:29am
v2

1 solution

Stack overflow in recursive programs generally means that some termination condition isn't right. Looking at your code (which I hope is not all of your program), each time QuickSortHelper is called, it returns a list one element larger than its input. (Hint: what happens to the Pivot element?) If you keep on doing that, (1) it will never terminate and (2) it will run out of memory.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900