首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >外壳排序算法

外壳排序算法
EN

Stack Overflow用户
提问于 2020-04-02 07:38:44
回答 1查看 40关注 0票数 0

我正在尝试使用shell排序算法实现一个数组。单击按钮后,程序将对数组进行排序,并将每个元素输出到列表框。但是,第一项输出始终为0。我已经包含了我的一段源代码和下面表格的一张照片;

代码语言:javascript
复制
 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

EN

回答 1

Stack Overflow用户

发布于 2020-04-02 07:45:20

问题出在这里:

代码语言:javascript
复制
    ReDim unstArray(i)
    ReDim unstArrayCopy(i)

在VB中,当你初始化一个数组时,你必须给它提供你想要使用的最大索引,而不是像在C#这样的其他语言中所期望的数组长度。

因此,您的代码创建了一个长度为i+1的数组,但是在填充该数组时,您只能从0循环到i。因此索引i处的最后一个元素将始终为零。

您应该将这些行中的初始化器设置为i-1。

VB Array Reference

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60982004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档