Friday, March 28, 2008

In Place Merge Sort

According to Wikipedia InPlaceMergeSort is a pretty fast sorting algorithm (O(n log n) on average, O(n log n) worst case and O(1) memory usage.) Sub InPlaceMergeSort(vArray As Variant, nLow0 As Integer, nHigh0 As Integer)
Dim nLow As Integer
Dim nHigh As Integer
Dim nMid As Integer
Dim nEndLow As Integer
Dim nStartHigh As Integer
Dim vTemp As Variant
Dim nCount As Integer nLow = nLow0
nHigh = nHigh0
If nLow >= nHigh Then
Exit Sub
End If nMid = (nLow + nHigh) \ 2 Call InPlaceMergeSort(vArray, nLow, nMid)
Call InPlaceMergeSort(vArray, nMid + 1, nHigh) nEndLow = nMid
nStartHigh = nMid + 1 While nLow <= nEndLow And nStartHigh <= nHigh
If vArray(nLow) < vArray(nStartHigh) Then
nLow = nLow + 1
Else
vTemp = vArray(nStartHigh)
For nCount = nStartHigh -1 To nLow Step -1
vArray(nCount + 1) = vArray(nCount)
Next
vArray(nLow) = vTemp
nLow = nLow + 1
nEndLow = nEndLow + 1
nStartHigh = nStartHigh + 1
End If
Wend
End Sub Sub sort(vArray As Variant)
Call InPlaceMergeSort(vArray, Lbound(vArray), Ubound(vArray))
End Sub

No comments: