对于少部分还在使用vb6的人来说,调用cdecl协议的函数,声明或用VB写带cdecl协议的函数,一般尽量放在 模块中,
但msvcrt中的quirkcSort()函数 对Double或Currency等带小数点的类型,无法正确排序,关键问题是出在 comparator
因为 comparator 要求返回值是long,所以我们要增加 comparator= IIF((a-b)>0,1,-1) 让返回 1或-1 这样的long值,
这样就能正确排序,虽然调用IIF(),是会影响性能,但依然是在我们能承受的范围。
以下以long和double为例子,排序20万条数字。
模块中:
Public Declare Function GetTickCount Lib "kernel32" () As Long
Public Declare Sub qsort CDecl Lib "msvcrt" ( _
ByRef pFirst As Any, _
ByVal lNumber As Long, _
ByVal lSize As Long, _
ByVal pfnComparator As Long)
Public Function Comparator CDecl(ByRef a _
As Double, ByRef b _
As Double) As Long
Comparator = IIf((a - b) > 0, 1, -1)
End Function
窗体中放入一个command按钮
Private Sub Command1_Click()
Dim z() As Double
Dim i As Long
Dim s As String
Dim t1 As Long
t1 = GetTickCount()
ReDim z(200000)
Randomize
For i = 0 To UBound(z)
z(i) = CDbl((Rnd * 100))
Next
qsort z(0), UBound(z) + 1, LenB(z(0)), AddressOf Comparator
MsgBox "20万Double排序计时:" & GetTickCount() - t1 & "毫秒"
For i = 199991 To UBound(z) '为节省时间,二十万个数据取最后10个数据看一下
Debug.Print z(i)
Next
End Sub
测试结果:20万double排序约 500毫秒左右。(编译成exe,约359毫秒左右)
测试结果2:20万long排序约182毫秒左右。(编译成exe,约46毫秒左右)