我正在尝试使用shell排序算法实现一个数组。单击按钮后,程序将对数组进行排序,并将每个元素输出到列表框。但是,第一项输出始终为0。我已经包含了我的一段源代码和下面表格的一张照片;
Dim randGen As New Random()
Dim unstArray() As Integer
Dim unstArrayCopy() As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'Generates random number to save in array.
Dim i As Integer = CInt(TextBox1.Text)
ReDim unstArray(i)
ReDim unstArrayCopy(i)
For x = 0 To i
unstArray(x) = randGen.Next(1, 10001)
Next
Array.Copy(unstArray, unstArrayCopy, i)
End Sub
Private Sub ShllSrtBtn_Click(sender As Object, e As EventArgs) Handles shllSrtBtn.Click
shellsort(unstArrayCopy, unstArrayCopy.GetUpperBound(0))
End Sub
Sub shellsort(ByRef shellSort() As Integer, ByVal max As Integer)
Dim stopp%, swap%, limit%, temp%, k%
Dim x As Integer = CInt((max / 2) - 1)
Do While x > 0
stopp = 0
limit = max - x
Do While stopp = 0
swap = 0
For k = 0 To limit
If shellSort(k) > shellSort(k + x) Then
temp = shellSort(k)
shellSort(k) = shellSort(k + x)
shellSort(k + x) = temp
swap = k
End If
Next k
limit = swap - x
If swap = 0 Then stopp = 1
Loop
x = CInt(x / 2)
Loop
For i = 0 To shellSort.GetUpperBound(0)
ListBox1.Items.Add(shellSort(i))
Next i
End Sub

发布于 2020-04-02 07:45:20
问题出在这里:
ReDim unstArray(i)
ReDim unstArrayCopy(i)在VB中,当你初始化一个数组时,你必须给它提供你想要使用的最大索引,而不是像在C#这样的其他语言中所期望的数组长度。
因此,您的代码创建了一个长度为i+1的数组,但是在填充该数组时,您只能从0循环到i。因此索引i处的最后一个元素将始终为零。
您应该将这些行中的初始化器设置为i-1。
https://stackoverflow.com/questions/60982004
复制相似问题