Quick Sort 2 : Array Sort « Data Type « VBA / Excel / Access / Word






Quick Sort 2

 
Sub Main()
   Dim myArray(4) As Double
   myArray(0) = 9
   myArray(1) = 11
   myArray(2) = 7
   myArray(3) = 4
   
   Call QSort(myArray, 0, 4)

   Debug.Print myArray(0)
   Debug.Print myArray(1)
   Debug.Print myArray(2)
   Debug.Print myArray(3)

End Sub

Sub QSort(sortArray() As Double, ByVal leftIndex As Integer, _
                                     ByVal rightIndex As Integer)
    Dim compValue As Double
    Dim I As Integer
    Dim J As Integer
    Dim tempNum As Double

    I = leftIndex
    J = rightIndex
    compValue = sortArray(Int((I + J) / 2))

    Do
        Do While (sortArray(I) < compValue And I < rightIndex)
            I = I + 1
        Loop
        Do While (compValue < sortArray(J) And J > leftIndex)
            J = J - 1
        Loop
        If I <= J Then
            tempNum = sortArray(I)
            sortArray(I) = sortArray(J)
            sortArray(J) = tempNum
            I = I + 1
            J = J - 1
        End If
    Loop While I <= J

    If leftIndex < J Then QSort sortArray(), leftIndex, J
    If I < rightIndex Then QSort sortArray(), I, rightIndex
End Sub

 








Related examples in the same category

1.VBA Bubble Sort
2.using dynamic arrays in bubble sort
3.Performing a Binary Search through an Array
4.Quick sort