Tabs467 - 2 months ago 16

Vb.net Question

This insertion sort is for sorting the array into ascending order, when it attempt to do so I receive an index out of range exception, when this happens "j" is 0 and "i" is 1. It tries to compare the value in the first element to the value in the element with an index of "-1" which doesn't exist. What changes can I make to make this code functional?

`Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click`

Dim i, j, element, length As Integer

Dim array(7) As Integer

array(0) = 5

array(1) = 2

array(2) = 7

array(3) = 6

array(4) = 9

array(5) = 1

array(6) = 4

array(7) = 8

length = array.Length

For i = 1 To length - 1

j = i

While j > 0 And array(j) < array(j - 1)

If array(j - 1) > array(j) Then

element = array(j)

array(j) = array(j - 1)

j = j - 1

array(j) = element

End If

End While

Next

For Index As Integer = 0 To 7

ListBox1.Items.Add(array(Index))

Next

End Sub

Answer Source

Your line saying

```
While j > 0 And array(j) < array(j - 1)
```

will give an index out of range error whenever `j`

is zero (because `j - 1`

will be `-1`

and you don't have a `array(-1)`

element).

Change that line to

```
While j > 0 AndAlso array(j) < array(j - 1)
```

so that the second part of the test is only evaluated if the first part is `True`

.