Bubble sort doesn't work

I've been staring at this code for a while - its probably something really simple. Can anyone tell me why this sort apparently has no effect on my data?

Public Type Individual
Data(1 To 11) As Long
End Type
Public Population(1 To 25) As Individual

Sub Sort()
Dim temp As Individual
For h = 1 To 24
If Population(h).Data(1) > Population(h + 1).Data(1) Then
temp = Population(h + 1)
Population(h + 1) = Population(h)
Population(h) = temp
End If
Next h
End Sub

Thanks in advance.

Comments

  • : I've been staring at this code for a while - its probably something really simple. Can anyone tell me why this sort apparently has no effect on my data?
    :
    : Public Type Individual
    : Data(1 To 11) As Long
    : End Type
    : Public Population(1 To 25) As Individual
    :
    : Sub Sort()
    : Dim temp As Individual
    : For h = 1 To 24
    : If Population(h).Data(1) > Population(h + 1).Data(1) Then
    : temp = Population(h + 1)
    : Population(h + 1) = Population(h)
    : Population(h) = temp
    : End If
    : Next h
    : End Sub
    :
    : Thanks in advance.
    :

    You need a nested loop, I believe. That code would make changes to the array but not enough to completely sort it.
    [code]
    Public Type Individual
    Data(1 To 11) As Long
    End Type
    Public Population(1 To 25) As Individual

    Sub Sort()
    Dim temp As Individual
    [b]Dim I As Long [blue]'Always Dim your variables![/blue]
    Dim h As Long[/b]
    [b]For I = 1 To 24[/b]
    For h = 1 To 24
    If Population(h).Data(1) > Population(h + 1).Data(1) Then
    temp = Population(h + 1)
    Population(h + 1) = Population(h)
    Population(h) = temp
    End If
    Next h
    [b]Next [blue]'You don't need to put "h", "I" or anything[/blue][/b]
    End Sub
    [/code]
    Hope this helps!
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion