日々の記録

ほどよく書いてきます。

VBAで実装するクイックソート(メモ)

2023年03月26日 11時21分18秒 | プログラム

サブルーチンとして次を定義しておく。

Sub QuickSort(arr As Variant, firstIndex As Long, lastIndex As Long)
    Dim pivot As Variant
    Dim pivotIndex As Long
    Dim leftIndex As Long
    Dim rightIndex As Long
    
    If firstIndex < lastIndex Then
        pivot = arr(lastIndex)
        pivotIndex = firstIndex - 1
        leftIndex = firstIndex
        
        For rightIndex = firstIndex To lastIndex - 1
            If arr(rightIndex) <= pivot Then
                pivotIndex = pivotIndex + 1
                Swap arr(pivotIndex), arr(rightIndex)
            End If
        Next rightIndex
        
        pivotIndex = pivotIndex + 1
        Swap arr(pivotIndex), arr(lastIndex)
        
        Call QuickSort(arr, firstIndex, pivotIndex - 1)
        Call QuickSort(arr, pivotIndex + 1, lastIndex)
    End If
End Sub

Sub Swap(ByRef a As Variant, ByRef b As Variant)
    Dim temp As Variant
    temp = a
    a = b
    b = temp
End Sub

 

呼び出しは次のようにする

Dim arr As Variant
arr = Array(4, 2, 3, 1, 5)
Call QuickSort(arr, 0, UBound(arr))

コメント    この記事についてブログを書く
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする
« ホールセンサーの動作確認 | トップ | エクセルで作る正規分布乱数 »

コメントを投稿

プログラム」カテゴリの最新記事