【问题标题】:Visual Basic Quicksort Algorithm crash - 'System.StackOverflowException'Visual Basic 快速排序算法崩溃 - 'System.StackOverflowException'
【发布时间】:2015-10-16 21:37:53
【问题描述】:

我目前正在尝试在 Visual Basic 中编写快速排序算法。

我最初通过寻找可以作为算法基础的预先编写的代码来尝试这个。但是,我发现的大部分代码都是用我几乎没有经验的语言编写的。

我也尝试过寻找伪代码示例。我已将我的代码与互联网上提供的伪代码示例进行了比较,但仍然无法让代码正确运行。

当前问题是“在 QuickSort.exe 中发生类型为 'System.StackOverflowException' 的未处理异常”,只要使用“intGeneratedData”数组中的任何随机生成的数据运行该过程。此错误指向过程的“Private Sub”行。

    Private Sub QuicksortAlgorithm(ByRef intGeneratedData() As Integer, ByVal intSize As Integer)
    Dim intPivotValue, intLower, intUpper, intSwapTemp As Integer

    If (intSize > 1) Then
        intPivotValue = intGeneratedData((Int((intSize * Rnd()) + 1)))
        intLower = 0
        intUpper = (intSize - 1)

        While intLower <= intUpper
            While intGeneratedData(intLower) < intPivotValue
                intLower += 1
            End While

            While intGeneratedData(intUpper) > intPivotValue
                intUpper -= 1
            End While

            'Swap lower and upper value
            If intLower <= intUpper Then
                intSwapTemp = intGeneratedData(intLower)
                intGeneratedData(intLower) = intGeneratedData(intUpper)
                intGeneratedData(intUpper) = intSwapTemp

                intLower += 1
                intUpper -= 1
            End If

        End While

        QuicksortAlgorithm(intGeneratedData, intLower)
        QuicksortAlgorithm(intGeneratedData, (intUpper - intLower))
    End If

End Sub

注意:调用算法时,'intSize' 始终是数组 'intGeneratedData' 的大小。

我觉得在此过程中我还没有提到其他错误,因为在我更改了多个导致此问题之前,我之前遇到了另一个错误。我一直试图让它工作几天但没有成功。如果此线程没有提供有关该问题的信息,我们深表歉意。

任何帮助将不胜感激。

【问题讨论】:

    标签: vb.net algorithm quicksort


    【解决方案1】:

    这是一种递归算法,您不能在函数中使用 return 语句提前退出它。在函数底部再调用两次 QuicksortAlgorithm。你的算法永远不会完成——它只会永远调用自己。如果我不得不猜测,我会说将其添加到函数的顶部:

    If intSize < 1 Then
       Return
    End If
    

    发件人:http://mark.random-article.com/weber/ada/week13.html

    见:

    递归要求

    ...您缺少退出条件

    退出条件或“停止案例”(正如书中所说)——我也听说过这被称为“基本案例”。这是函数最终返回的状态,不再调用自身。退出条件是递归函数的关键组成部分。如果你没有一个在那里,它永远不会退出。 退出条件通常是递归函数中的第一件事。

    【讨论】:

    • 感谢您的快速响应,我尝试这样做但是它在同一位置产生了相同的错误:(
    • 嗯..也许
    • 所以“如果 intSize
    • 按照链接上设置的示例,效果很好。干杯
    猜你喜欢
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 2016-11-24
    • 2018-05-17
    相关资源
    最近更新 更多