VBA数组排序函数? [英] VBA array sort function?

查看:104
本文介绍了VBA数组排序函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 VBA 中的数组寻找合适的排序实现.首选快速排序.或任何其他 排序算法 除了冒泡或合并就足够了.

I'm looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other sort algorithm other than bubble or merge would suffice.

请注意,这是与 MS Project 2003 配合使用,因此应避免使用任何 Excel 本机函数和任何与 .net 相关的内容.

Please note that this is to work with MS Project 2003, so should avoid any of the Excel native functions and anything .net related.

推荐答案

看看 这里:
引用的来源 (allexperts.com) 已关闭,但这里有相关的 作者 评论:

Take a look here:
The referenced source (allexperts.com) has since closed, but here are the relevant author comments:

网络上有许多算法可用于排序.最通用且通常最快的是快速排序算法.下面是它的一个函数.

There are many algorithms available on the web for sorting. The most versatile and usually the quickest is the Quicksort algorithm. Below is a function for it.

通过传递带有下数组边界(通常是0)和的值数组(字符串或数字;无关紧要)来调用它>上阵列边界(即UBound(myArray).)

Call it simply by passing an array of values (string or numeric; it doesn't matter) with the Lower Array Boundary (usually 0) and the Upper Array Boundary (i.e. UBound(myArray).)

示例:调用 QuickSort(myArray, 0, UBound(myArray))

完成后,myArray 将被排序,你可以用它做你想做的事.
(来源:archive.org)

When it's done, myArray will be sorted and you can do what you want with it.
(Source: archive.org)

Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)
  Dim pivot   As Variant
  Dim tmpSwap As Variant
  Dim tmpLow  As Long
  Dim tmpHi   As Long

  tmpLow = inLow
  tmpHi = inHi

  pivot = vArray((inLow + inHi) \ 2)

  While (tmpLow <= tmpHi)
     While (vArray(tmpLow) < pivot And tmpLow < inHi)
        tmpLow = tmpLow + 1
     Wend

     While (pivot < vArray(tmpHi) And tmpHi > inLow)
        tmpHi = tmpHi - 1
     Wend

     If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow)
        vArray(tmpLow) = vArray(tmpHi)
        vArray(tmpHi) = 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

请注意,这仅适用于一维(又名普通"?)数组.(有一个有效的多维数组 QuickSort 此处.)

Note that this only works with single-dimensional (aka "normal"?) arrays. (There's a working multi-dimensional array QuickSort here.)

这篇关于VBA数组排序函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆