2

I've unfortunately inherited some VBA code which uses LinkedLists in VBA but nothing is sorted, and needs to be sorted.

LinkedList example: http://support.microsoft.com/kb/166394

I'm trying to do a quicksort on the items by translating the following code to a LinkedList: VBA array sort function?

But I'm having a hard time following the logic of the function to determine how to translate it to a non-numbered system like a Linked List.

Could someone help comment up the code to explain what is happening, or possibly help in the translation?

Community
  • 1
  • 1
Doug
  • 6,446
  • 9
  • 74
  • 107

1 Answers1

2

First, you will need a Linked List object. I will use an array for the example. Let's take 5 nodes for the simplicity of the example.

'Declaration of the array
Dim LinkedList(0 To 4) As Node

Now, time to fill the array. We say that the variable head is the head of our LinkedList :

Dim i As Integer
i = 0

Dim currentNode As Node
Set currentNode = head.pnext

While Not currentNode.pnext Is currentNode 'walk rest of list to end
    LinkedList(i) = currentNode
    i = i + 1
    Set currentNode = currentNode.pnext      'current pointer to next node
Wend

Our LinkedList is now filled, we can use the Quicksort. We launch the initial call with this line :

QuickSort LinkedList, LBound(LinkedList), UBound(LinkedList)

And we adapt a little the function :

Public Sub QuickSort(vArray As Node, inLow As Long, inHi As Long)

  Dim pivot   As Integer
  Dim tmpSwap As Integer
  Dim tmpLow  As Long
  Dim tmpHi   As Long

  tmpLow = inLow
  tmpHi = inHi

  pivot = vArray((inLow + inHi) \ 2).Key

  While (tmpLow <= tmpHi)

     While (vArray(tmpLow).Key < pivot And tmpLow < inHi)
        tmpLow = tmpLow + 1
     Wend

     While (pivot < vArray(tmpHi).Key And tmpHi > inLow)
        tmpHi = tmpHi - 1
     Wend

     If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow).Key
        vArray(tmpLow).Key = vArray(tmpHi).Key
        vArray(tmpHi).Key = tmpSwap
        tmpLow = tmpLow + 1
        tmpHi = tmpHi - 1
     End If

  Wend

  If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
  If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi

End Sub

I think it's good. Tell me if there is a problem or a misunderstanding.

Adrien Lacroix
  • 3,502
  • 1
  • 20
  • 23
  • Sorry it took me so long to accept this answer. I don't know how I missed this had been answered. – Doug Jan 01 '18 at 15:31