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