0
這種插入排序是爲了將數組按升序排序,當它試圖這樣做時,我收到一個索引超出範圍的異常,當這種情況發生時,「j」爲0,「i」爲1它嘗試比較值在第一個元素中的索引值爲「-1」的元素中不存在的值。我可以做些什麼改變來使這些代碼正常工作?爲什麼我在插入排序時收到索引超出範圍的異常?
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