2013-05-14 35 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