2013-05-14 77 views
2

我不幸地继承了一些VBA代码,它在VBA中使用LinkedLists,但没有排序,需要排序。VBA中的LinkedList上的快速排序

LinkedList的例子: http://support.microsoft.com/kb/166394

我想要做的项目由以下代码翻译成一个LinkedList一个快速排序: VBA array sort function?

但我有逻辑下很难的功能来确定如何将其转换为像链接列表这样的非编号系统。

有人可以帮助评论代码来解释发生了什么,或可能有助于翻译吗?

回答

2

首先,您需要一个链接列表对象。我将使用一个数组作为示例。为了简化示例,我们假设有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 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 

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

+0

对不起,花了这么长的时间才接受这个答案。我不知道我是如何错过了这个回答。 – Doug 2018-01-01 15:31:05