Reputation: 159
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
This is the code for my bubble sort for a project but when I press the button that sorts and displays the array I get the error: "index was outside the bounds of the array"
on the line
If Names(ComparisonNumber) > Names(ComparisonNumber + 1) Then
Any ideas as to why? Thanks
Upvotes: 0
Views: 110
Reputation: 239764
If PatientCount
is the number of items being stored in Names
(you've not shown the definition for either of these) then the indexes for Names
run from 0 to PatientCount - 1
.
So, in the last iteration, when ComparisonNumber
is equal to PatientCount - 1
, you attempt to access the items at indexes PatientCount - 1
and PatientCount
- but that second index is invalid.
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
Also, these lines seem wrong:
lstPatientHeights.Items.Add(Heights(i))
lstPatientWeights.Items.Add(Weights(i))
Because you haven't been sorting Heights
and Weights
in the same way that you have been sorting Names
, so they're going to still be in their original order. You either should be performing the same swaps to all of these when you decide to perform a swap, or you ought to be storing objects in a single (array?) that have 3 properties - Name
, Height
and Weight
and then be swapping these objects.
Upvotes: 2