gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
帮我写一段冒泡排序的代码VBA
- User
帮我写一段冒泡排序的代码VBA
- 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函数将排序后的数组打印出来。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.