C ++快速排序给我Stack Overflow

时间:2017-09-21 04:37:51

标签: c++ sorting stack-overflow quicksort

我被赋予了伪代​​码,我几乎都有正确的形式,但我不知道为什么每次尝试在Visual Studio中运行快速排序时它都会给我一个Stack Overflow。以下是我所做的功能。

template <typename T>
void quickSort(T list[], int lowerBound, int upperBound)
{ 
int i = lowerBound;
int j = upperBound;
T tmp;
T pivot = list[(lowerBound + upperBound)] / 2;

while (i <= j)
{
    while (list[i] < pivot)
    {
        i = i + 1;
    }

    while (list[j] > pivot)
    {
        j = j - 1;
    }

    if (i <= j)
    {
        tmp = list[i];
        list[i] = list[j];
        list[j] = tmp;
        i = i + 1;
        j = j - 1;
    }
}
if (lowerBound < j)
    quickSort(list, lowerBound, j);
if (i < upperBound)
    quickSort(list, i, upperBound);
}

谢谢!

1 个答案:

答案 0 :(得分:2)

T pivot = list[(lowerBound + upperBound)] / 2;更改为 T pivot = list[(lowerBound + upperBound)/2];