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
        Dim temp As Integer
        
        For i = 0 To UBound(arr) - 1
            For j = 0 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
    

    你可以在调用这个过程之前,将需要排序的数组传递给BubbleSort过程。例如:

    Sub Main()
        Dim array() As Integer
        
        ' 定义需要排序的数组
        array = Array(3, 1, 5, 2, 4)
        
        ' 调用冒泡排序
        BubbleSort array
        
        Dim i As Integer
        ' 输出排序后的结果
        For i = 0 To UBound(array)
            Debug.Print array(i)
        Next i
    End Sub
    

    这个示例中,将会输出排序后的结果:

    1
    2
    3
    4
    5
    

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