user2956578
user2956578

Reputation: 71

Out of Bounds error when Implementing an insertion sort

It seems that VB.NET evaluates both sides of the Boolean condition While j >= 1 And Card(j - 1) > NextCard, which will of course lead to an out of bounds error.

Other languages I have programmed in would have evaluated the left condition first and exited the loop before the second condition would cause the program to crash.

Can anyone see an obvious solution or do I just need to make turn the algorithm into a convoluted mess?

Sub Main()
    Dim card() As Integer = {7, 4, 6, 8, 1, 5}
    Insertion_Sort(card)
    For Each item In card
        Console.WriteLine(item)
    Next
End Sub

Sub Insertion_Sort(ByRef Card() As Integer)
    Dim NextCard
    Dim j As Integer

    For i = 1 To Card.Length - 1
        NextCard = Card(i)
        j = i
        While j >= 1 And Card(j - 1) > NextCard
            Card(j) = Card(j - 1)
            j -= 1
        End While
        Card(j) = NextCard
    Next
End Sub

Upvotes: 3

Views: 86

Answers (1)

vbnet3d
vbnet3d

Reputation: 1151

As Capellan suggested, short-circuit evaluation can be done using the AndAlso keyword in place of And:

While j >= 1 AndAlso Card(j - 1) > NextCard
     Card(j) = Card(j - 1)
     j -= 1
End While

This causes VB.Net to evaluate the first expression first, and then, only if the first expression is true, it evaluates the second.

I suggest you also review the MSDN page: https://msdn.microsoft.com/en-us/library/cb8x3kfz.aspx

Upvotes: 2

Related Questions