首页 > 解决方案 > 有没有办法修复冒泡排序中的索引错误?

问题描述

我正在尝试在 vb 中编写冒泡排序,并且我的算法是正确的,但它总是说“索引超出了数组的范围。” 我不知道如何解决。我将把代码放在下面,任何帮助都会很好。

    Sub Main()
    Dim unsorted() As Integer = {17, 19, 12, 10, 15, 20}
    Dim n As Integer = unsorted.Length
    Dim swapped As Boolean = True
    Dim temp
    Dim list As String = ""

    While n > 0 And swapped = True
        For a = 0 To n - 1
            If unsorted(a) > unsorted(a + 1) Then
                temp = unsorted(a)
                unsorted(a) = unsorted(a + 1)
                unsorted(a + 1) = temp
                swapped = True
            End If
        Next
    End While
    For Each number In unsorted
        number &= list & " "
    Next
    Console.WriteLine(list)
    Console.ReadLine()
End Sub

标签: vb.netsorting

解决方案


我希望这段代码对你有用:

Private unsorted() As Byte = {17, 19, 12, 10, 15, 20}

Sub Main()
    Dim temp As Byte

    For pass = 1 To unsorted.Length - 1
        For i = 0 To unsorted.Length - 2
            If unsorted(i) > unsorted(i + 1) Then
                temp = unsorted(i)
                unsorted(i) = unsorted(i + 1)
                unsorted(i + 1) = temp
            End If
        Next i
    Next pass

    Dim output As String = ""

    For i = 0 To unsorted.Length - 1
        output &= unsorted(i).ToString + vbNewLine
    Next

    Console.WriteLine(output)

    Console.ReadKey()
End Sub

结果如下:

冒泡排序算法成功

享受冒泡排序。


推荐阅读