Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

帮我写一段冒泡排序的代码VBA

  1. User

    帮我写一段冒泡排序的代码VBA

  2. Assistant

    以下是一段使用 VBA 语言编写的冒泡排序代码:

    Sub BubbleSort(arr() As Integer)
        Dim i As Integer, j As Integer, temp As Integer, n As Integer
        n = UBound(arr) - LBound(arr) + 1 ' 获取数组长度
        For i = LBound(arr) To UBound(arr) - 1
            For j = LBound(arr) To UBound(arr) - i - 1
                If arr(j) > arr(j + 1) Then ' 如果当前元素比下一个元素大,则交换它们的位置
                    temp = arr(j)
                    arr(j) = arr(j + 1)
                    arr(j + 1) = temp
                End If
            Next j
        Next i
    End Sub
    

    使用示例:

    Sub TestBubbleSort()
        Dim arr() As Integer
        Dim i As Integer
        arr = Array(5, 2, 8, 9, 1)
        BubbleSort arr
        For i = LBound(arr) To UBound(arr)
            Debug.Print arr(i)
        Next i
    End Sub
    

    此代码定义了一个名为 BubbleSort 的子程序,用于对输入的整数数组进行冒泡排序。通过传入一个整数数组作为参数,我们可以使用 BubbleSort arr 来调用此子程序,并对数组进行排序。最终我们可以通过 Debug.Print 函数将排序后的数组打印出来。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.