"Index was outside the bounds of the array" 我的排序程序有问题

"Index was outside the bounds of the array" problem with my sort program

我有一个使用 vb.net 框架的程序,它似乎出错了。它只是我以前使用过的一种 BubbleSort 算法,但由于某种原因它无法正常工作。要启动用户放置在列表框中的 txt 文件中的程序,这部分工作正常。输入下一个表单是使用 BubbleSort 对文本框中的信息进行排序的地方,单击按钮后,列表框将清除并将新排序的列表粘贴到同一个列表框中。那是错误出现的时候。

代码如下:

Private Sub btnNameSort_Click(sender As Object, e As EventArgs) Handles btnNameSort.Click

    lstSortArray.Items.Clear()

    Dim Data() As String = DataEntry.lstPatientArray.Items.Cast(Of Object).Select(Function(o) DataEntry.lstPatientArray.GetItemText(o)).ToArray

    Count = DataEntry.lstPatientArray.Items.Count

    Dim Swapped As Boolean
    Dim comparisonNo As Integer
    Dim temp As String
    Dim i As Integer

    Swapped = True

    While Swapped = True
        Swapped = False
        comparisonNo = 1
        While comparisonNo < Count
            If Data(comparisonNo) > Data(comparisonNo + 1) Then
                temp = Data(comparisonNo)
                Data(comparisonNo) = Data(comparisonNo + 1)
                Data(comparisonNo + 1) = temp
                Swapped = True
            End If
            comparisonNo = comparisonNo + 1
        End While
    End While

    For i = 1 To Count
        lstSortArray.Items.Add(Data(Count))
    Next

End Sub

出现错误的行: If Data(comparisonNo) > Data(comparisonNo + 1) Then

DataEntry.lstPatientArray 是另一个表单上的列表框,如果您需要知道,Count 已在表单的开头声明为整数。

我是编码新手,所以我们将不胜感激。谢谢!

.net 中的数组是从零开始的。数组第一个元素的索引为 0。当在代码中初始化数组时,正如您在此处所做的那样,最后一个元素的索引将比 Count 小 1。请记住我们从零开始。

我们不需要 i,因为我们正在使用 For Each 循环来显示结果。

在第一个循环中,您不想设置 comparisonNo = 1。数组索引从零开始。为了使索引保持在范围内,我们需要从 Length 中减去 2。索引结束时比 Length 少一个,当我们与 i +1 比较时,我们需要减去另一个 1.

**EDIT**

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim a() = {"Monty Reyes", "Kier Burke", "Kallum Wiley", "Raja Krueger", "Clarissa Webb", "Connah Mathews", "Alisa Bassett", "Emmeline Mills"}
    Dim Swapvalue As String
    For ii = 0 To a.Length - 2
        For i = 0 To a.Length - 2
            If a(i) > a(i + 1) Then
                Swapvalue = a(i)
                a(i) = a(i + 1)
                a(i + 1) = Swapvalue
            End If
        Next
    Next

    For Each st In a
        Debug.Print(st)
    Next
End Sub

当然你可以随时做...

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim a() = {"Monty Reyes", "Kier Burke", "Kallum Wiley", "Raja Krueger", "Clarissa Webb", "Connah Mathews", "Alisa Bassett", "Emmeline Mills"}
    Array.Sort(a)
    For Each st In a
        Debug.Print(st)
    Next
End Sub