2

不幸的是,我继承了一些在 VBA 中使用 LinkedLists 的 VBA 代码,但没有排序,需要排序。

链表示例: http: //support.microsoft.com/kb/166394

我正在尝试通过将以下代码转换为 LinkedList 来对项目进行快速排序: VBA 数组排序函数?

但是我很难按照函数的逻辑来确定如何将其转换为像链接列表这样的非编号系统。

有人可以帮助评论代码以解释正在发生的事情,或者可能帮助翻译吗?

4

1 回答 1

2

首先,您需要一个 Linked List 对象。我将使用一个数组作为示例。为简单起见,我们采用 5 个节点。

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

现在,是时候填充数组了。我们说变量head是我们的头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

我们LinkedList现在已经填满了,我们可以使用Quicksort。我们使用这一行启动初始调用:

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

我们稍微调整一下函数:

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

我认为这很好。告诉我是否有问题或误解。

于 2013-05-14T18:48:31.313 回答