萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Excel 教學 >> Excel 綜合

VBA 陣列排序:氣泡排序法實作升冪/降冪與中文快速排序

VBA 內建無陣列排序方法,需自行實作。本文提供氣泡排序法(升冪/降冪)與快速排序法(支援中文字串)完整 Function 程式碼。

① 氣泡排序法:升冪

Function UP(x() As Variant) As Variant()
    Dim i As Long, j As Long, tmp As Variant
    Dim d() As Variant
    ReDim d(LBound(x) To UBound(x))
    d = x
    
    If LBound(x) = UBound(x) Then
        UP = d
        Exit Function
    End If
    
    For i = LBound(x) To UBound(x) - 1
        For j = i + 1 To UBound(x)
            If d(j) < d(i) Then
                tmp = d(j): d(j) = d(i): d(i) = tmp
            End If
        Next j
    Next i
    UP = d
End Function

② 氣泡排序法:降冪

Function Down(x() As Variant) As Variant()
    Dim i As Long, j As Long, tmp As Variant
    Dim d() As Variant
    ReDim d(LBound(x) To UBound(x))
    d = x
    
    If LBound(x) = UBound(x) Then
        Down = d
        Exit Function
    End If
    
    For i = LBound(x) To UBound(x) - 1
        For j = i + 1 To UBound(x)
            If d(j) > d(i) Then
                tmp = d(j): d(j) = d(i): d(i) = tmp
            End If
        Next j
    Next i
    Down = d
End Function

③ 快速排序法:支援中文字串(StrComp 比較)

Sub QuickSort2(MyArray() As Variant, L As Long, R As Long)
    Dim I As Long, J As Long
    Dim X As Variant, Y As Variant
    Dim tp As Integer: tp = 1  ' 1=vbBinaryCompare, 0=vbTextCompare
    
    I = L: J = R
    X = MyArray((L + R) \ 2)
    
    Do While I <= J
        Do While StrComp(MyArray(I), X, tp) < 0 And I < R: I = I + 1: Loop
        Do While StrComp(X, MyArray(J), tp) < 0 And J > L: J = J - 1: Loop
        If I <= J Then
            Y = MyArray(I)
            MyArray(I) = MyArray(J)
            MyArray(J) = Y
            I = I + 1
            J = J - 1
        End If
    Loop
    
    If L < J Then QuickSort2 MyArray, L, J
    If I < R Then QuickSort2 MyArray, I, R
End Sub

' 使用範例
Sub TestQuickSort()
    Dim arr() As Variant
    arr = Array("大", "眾", "計", "算", "機", "學", "習", "網")
    QuickSort2 arr, 0, UBound(arr)
    Dim s As String, k As Long
    For k = LBound(arr) To UBound(arr)
        s = s & arr(k) & " | "
    Next
    MsgBox s  ' 顯示排序結果
End Sub

效能比較與建議

演算法 時間複雜度 適用資料量 中文支援
氣泡排序O(n²)< 1,000 筆需自行處理 StrComp
快速排序O(n log n) 平均> 1,000 筆內建 StrComp 正確比較中文
Excel 工作表排序高度優化任何量級最佳

實務建議

  • 資料量大、頻繁排序 → 直接用工作表 Range.Sort 或 WorksheetFunction.Sort (Excel 365)。
  • 記憶體中陣列小量排序 → 快速排序法效能佳。
  • 中文排序務必用 StrComp(..., vbTextCompare)(tp=0)依語言規則排序,而非位元組碼。
copyright © 萬盛學電腦網 all rights reserved