【问题标题】:Sort array in VBAVBA中的排序数组
【发布时间】:2018-01-31 02:57:30
【问题描述】:

我有一个 182.123 大小的数组,我想按数组类的特定属性对它们进行排序。该类称为 CFlujo,我想对它们进行排序的属性是一个名为 id_flujo 的字符串。到目前为止,我正在做这样的冒泡排序,但这需要的时间太长了:

Sub sort_arreglo(arreglo As Variant)
For x = LBound(arreglo) To UBound(arreglo)
For y = x To UBound(arreglo)
    Dim aux As CFlujo
    aux = New CFlujo
  If UCase(arreglo(y).id_flujo) < UCase(arreglo(x).id_flujo) Then
    Set aux = arreglo(y)
    Set arreglo(y) = arreglo(x)
    Set arreglo(x) = aux
  End If
 Next y
Next x
End Sub

到目前为止,我已经研究了Selection Sort,但我知道你不能从数组中删除项目,所以我不能创建两个列表来将值从一个到另一个排序。我可以将我的数据收集起来,但我在数据质量方面遇到了麻烦,除非我事先分配内存(比如在数组中)。

【问题讨论】:

标签: vba excel sorting


【解决方案1】:

您可以采取一些措施来缩短执行时间:

  • 加载数组中的所有属性
  • 排序一些指针而不是对象
  • 使用更好的算法,例如QucikSort

以你为例:

Sub Sort(arreglo As Variant)
  Dim cache, vals(), ptrs() As Long, i As Long

  ReDim vals(LBound(arreglo) To UBound(arreglo))
  ReDim ptrs(LBound(arreglo) To UBound(arreglo))

  ' load the properties and fill the pointers
  For i = LBound(arreglo) To UBound(arreglo)
    vals(i) = UCase(arreglo(i).id_flujo)
    ptrs(i) = i
  Next

  ' sort the pointers
  QuickSort vals, ptrs, 0, UBound(vals)

  ' make a copy
  cache = arreglo

  ' set the value for each pointer
  For i = LBound(arreglo) To UBound(arreglo)
    Set arreglo(i) = cache(ptrs(i))
  Next
End Sub


Private Sub QuickSort(vals(), ptrs() As Long, ByVal i1 As Long, ByVal i2 As Long)
  Dim lo As Long, hi As Long, p As Long, tmp As Long
  lo = i1
  hi = i2
  p = ptrs((i1 + i2) \ 2)

  Do
    While vals(ptrs(lo)) < vals(p): lo = lo + 1: Wend
    While vals(ptrs(hi)) > vals(p): hi = hi - 1: Wend

    If lo <= hi Then
      tmp = ptrs(hi)
      ptrs(hi) = ptrs(lo)
      ptrs(lo) = tmp
      lo = lo + 1
      hi = hi - 1
    End If
  Loop While lo <= hi

  If i1 < hi Then QuickSort vals, ptrs, i1, hi
  If lo < i2 Then QuickSort vals, ptrs, lo, i2
End Sub

【讨论】:

  • 如果最终用户会看到结果,我建议使用 Natural Number Comparison 比较值
  • 180.000 个值需要大约 10 秒,所以我想说它解决了这个问题,非常感谢
猜你喜欢
  • 2010-09-14
  • 2018-12-28
  • 1970-01-01
  • 1970-01-01
  • 2017-08-20
  • 2013-03-10
  • 2021-10-30
  • 2017-06-01
  • 2022-01-28
相关资源
最近更新 更多