2017-10-18 62 views
0

我想快速排序,但是我在VB.net中遇到堆棧溢出異常。快速排序中的堆棧溢出異常

排序工作正常,當x = 3,間歇當x = 5,有一次排序名單的一半,當x = 10

請指教,謝謝

Dim x As Integer = 10 
    Dim numArrray(x - 1) As Integer 

    For i = 0 To x - 1 
     Randomize() 
     numArrray(i) = CInt(Rnd() * 9) 
    Next 

    Quicksort(numArrray, 0, numArrray.Length - 1) 

    For i = 0 To x - 1 
     Console.Write(numArrray(i)) 
    Next 
    Console.ReadLine() 
End Sub 

Sub Quicksort(ByVal array() As Integer, ByVal min As Integer, ByVal max As Integer) 
    Dim pivot As Integer 

    If min < max Then 
     pivot = partition(array, min, max) 
     Quicksort(array, min, pivot - 1) 
     Quicksort(array, pivot + 1, max) 
    End If 
End Sub 

Function partition(ByVal array() As Integer, ByVal min As Integer, ByVal max As Integer) As Integer 
    Dim pivot As Integer = array(max) 
    Dim count As Integer = min - 1 
    Dim placeholder As Integer 

    For i = min To max - 1 
     If array(i) < pivot Then 
      count += 1 
      placeholder = array(count) 
      array(count) = array(i) 
      array(i) = placeholder 
     End If 
    Next 
    If array(max) < array(count + 1) Then 
     placeholder = array(count + 1) 
     array(count + 1) = array(max) 
     array(max) = placeholder 
    End If 
    Return count 

End Function 
+0

這不會編譯,你有沒有嘗試過調試和步進? – Codexer

+1

由於它的堆棧溢出,它將在嵌套調用Quicksort,看着分區我認爲你有一個界限的錯誤,按照這個版本的算法https://en.wikipedia.org/wiki/Quicksort你應該返回計數+ 1從分區,你當前的實施計數可以開始低於分鐘並保持這種方式,這將是一個無限迴歸,因爲你的嵌套調用會有相同的輸入(即如果你返回count = min - 1,那麼你做一個遞歸調用返回Quicksort(array,pivot + 1,max)== Quicksort(array,min,max) – tolanj

+0

@tolanj這是排序謝謝! – Chloe

回答

2

自一堆棧溢出它將在對Quicksort的嵌套調用,看着分區我認爲你有一個界限的錯誤,根據算法的這個版本en.wikipedia.org/wiki/Quicksort你應該返回count + 1從分區,在你的當前的實現計數可以在min下開始,並保持這種方式,這將是一個無限的迴歸,因爲你的嵌套調用會有相同的輸入(即如果y ou return count = min - 1然後你做一個遞歸調用回Quicksort(array,pivot + 1,max)== Quicksort(array,min,max)