2017-09-21 63 views
-1

我被給了僞代碼,我幾乎有它的形式是正確的,但我不明白爲什麼它會給我一個堆棧溢出每次我嘗試在Visual Studio中快速排序。以下是我所做的功能。C++快速排序給我堆棧溢出

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

我輕度困惑。我在想,你的快速排序總是會引導你到這個網站。這是我需要睡覺的標誌。 – DrZoo

+1

不應該透視列表[(lowerBound + upperBound)/ 2]? – thebenman

+0

@thebenman你是完全正確的。謝謝! – DavidM

回答

2

變化T pivot = list[(lowerBound + upperBound)]/2;T pivot = list[(lowerBound + upperBound)/2];