I'm doing a crash course in getting back into programming and I'm trying to write code for Quick Sort. Code runs great for an array that I code, but when I start randomizing things, it's throwing the error.

I believe the error may have something to do with values already in the array that are duplicates

    public static void SortArray<T>(T[] array) where T : IComparable<T>
    {
        QuickSort(array, 0, array.Length - 1);
    }

    public static void QuickSort<T>(T[] array, int left, int right)
        where T : IComparable<T>
    {
        int i = left;
        int j = right;

        var pivot = array[(left + right) / 2];

        while (i <= j)
        {
            while (array[i].CompareTo(pivot) < 0)
            {
                i++;
            }
            while (array[j].CompareTo(pivot) > 0)
            {
                j--;
            }

            if (i <= j)
            {
                var temp = array[i];
                array[i] = array[j];
                array[j] = temp;
                i++;
                j--;
            }
        }
        if (left < j)
        {
            QuickSort(array, left, i);
        }
        if (i < right)
        {
            QuickSort(array, i, right);
        }
    }

It's throwing System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was thrown.'

0 Answers