Public Class Form3
Public Swapped As Boolean
Public ComparisonNumber As Integer
Dim Temp As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Swapped = True
While Swapped = True
Swapped = False
ComparisonNumber = 0
While ComparisonNumber < PatientCount
If Names(ComparisonNumber) > Names(ComparisonNumber + 1) Then
Temp = Names(ComparisonNumber)
Names(ComparisonNumber) = Names(ComparisonNumber + 1)
Names(ComparisonNumber + 1) = Temp
Swapped = True
End If
ComparisonNumber = ComparisonNumber + 1
End While
End While
For i = 0 To PatientCount
lstPatientNames.Items.Add(Names(i))
lstPatientHeights.Items.Add(Heights(i))
lstPatientWeights.Items.Add(Weights(i))
Next
End Sub
End Class
这是我对项目进行冒泡排序的代码,但是当我按下排序并显示数组的按钮时,我会收到错误: "index was outside the bounds of the array"
就行了
If Names(ComparisonNumber) > Names(ComparisonNumber + 1) Then
为什么有任何想法? 感谢
答案 0 :(得分:2)
如果PatientCount
是Names
中存储的项目数(您没有显示其中任何一项的定义),那么Names
的索引将从0运行到{{ 1}}。
因此,在上一次迭代中,当PatientCount - 1
等于到ComparisonNumber
时,您尝试访问索引PatientCount - 1
和PatientCount - 1
处的项目 - 但第二个索引无效。
PatientCount
此外,这些线条似乎错了:
Swapped = True
While Swapped = True
Swapped = False
ComparisonNumber = 0
While ComparisonNumber < PatientCount - 1 'Changed here
If Names(ComparisonNumber) > Names(ComparisonNumber + 1) Then
Temp = Names(ComparisonNumber)
Names(ComparisonNumber) = Names(ComparisonNumber + 1)
Names(ComparisonNumber + 1) = Temp
Swapped = True
End If
ComparisonNumber = ComparisonNumber + 1
End While
End While
For i = 0 To PatientCount - 1 'And here
lstPatientNames.Items.Add(Names(i))
lstPatientHeights.Items.Add(Heights(i))
lstPatientWeights.Items.Add(Weights(i))
Next
因为您没有按照排序 lstPatientHeights.Items.Add(Heights(i))
lstPatientWeights.Items.Add(Weights(i))
的相同方式对Heights
和Weights
进行排序,所以它们仍将保持其原始顺序。当您决定执行交换时,您应该对所有这些进行相同的交换,或者您应该将对象存储在具有3个属性的单个(数组?)中 - Names
,Name
和Height
然后交换这些对象。