我正在尝试快速排序但是我在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 :(得分:2)
由于堆栈溢出,它将在Quicksort的嵌套调用中,查看分区我认为你有一个边界错误,根据这个算法版本en.wikipedia.org/wiki/Quicksort你应该返回count + 1来自分区,你当前的实现计数可以在min以下开始并保持这种无限回归的方式,因为你的嵌套调用将具有相同的输入(即如果你返回count = min - 1然后你做一个递归回调到Quicksort(array,pivot + 1,max)== Quicksort(array,min,max)