Hi all,
I am trying to implement quick-sort code in vba. Everything seems to work fine until when i am calling the recursive procedures for partitioning the master array into smaller chunks. I can't retrieve correctly the new boundaries for the sub-arrays. Variable "newlngRight" is not returned with the correct value.Any help will be much appreciated.
I use a main procedure to create the array (Load_Integers(varArray() As Long, length)) where values from range A1 to A6 are passed to the array (for testing purposes) and then code is as follows:
Thank you in advanceCode:Option Explicit
Option Base 1
Public ComparisonCounter As Long
Public left As Long, right As Long
Public newlngRight As Long, i As Long, j As Long
Sub PartitionQuickSort(varArray() As Long, lngLeft As Long, lngRight As Long)
'Declare pivot. Here is the first element of the array
Dim pivot As Long
pivot = varArray(lngLeft)
'i and j start from the position pivot + 1
i = 2
j = 2
For j = j To lngRight
If varArray(j) < pivot Then
SwapItems varArray(), i, j
i = i + 1
End If
Next j
'Bring pivot to its right position
SwapItems varArray, 1, i - 1
newlngRight = i - 1
End Sub
Sub Load_Integers(varArray() As Long, length As Long)
Dim k As Integer
ReDim varArray(length)
k = 0
For k = 1 To length
varArray(k) = Range("a" & k)
Next k
left = LBound(varArray)
right = UBound(varArray)
End Sub
Sub ComparisonsAndQuickSort(arr() As Long, lower As Long, upper As Long)
If lower < upper Then
PartitionQuickSort arr(), lower, upper
'ComparisonCounter = ComparisonCounter + (upper - 1)
ComparisonsAndQuickSort arr, lower, newlngRight
ComparisonsAndQuickSort arr, newlngRight + 1, upper
End If
End Sub
Sub SwapItems(arrSwap() As Long, Item1 As Long, Item2 As Long)
'Swap not sorted items
Dim temp As Integer
temp = arrSwap(Item2)
arrSwap(Item2) = arrSwap(Item1)
arrSwap(Item1) = temp
End Sub
George