Sorting Different Types
My version of SortArray sorts arrays of Variants. This is the most flexible way to define the procedure, but it won’t help if you have an array of Integers or Strings to sort. You can pass an Integer argument to a Variant parameter, but you can’t pass an array of Integers to a Variant array parameter. All those elements must be lined up in a row, and Basic must know the distance between them, which will be different for Integers than for Variants.
One solution is to put anything you want to sort in a Variant array. You can stuff the array with strings, integers, or real numbers, and SortArray will do the right thing with them. But it won’t necessarily be fast. You probably won’t see any difference if you’re sorting 150 integers or 50 strings. But if you’re doing the Mondo Double Sort From Down Under, you’ll want to write a separate SortArrayDouble for it. This process is so mechanical that you might be tempted to do it with conditional compilation:
# If SortArrayType = 0 Then
Sub SortArray(aTarget() As Variant, iFirst As Integer, __
iLast As Integer, helper As ISortHelper)
Dim vSplit As Variant
# ElseIf SortArrayType = 1 Then
Sub SortArray(aTarget() As Integer, iFirst As Integer, _
iLast As Integer, helper As ISortHelper)
Dim vSplit As Integer
# ElseIf SortArrayType = 2 Then
Sub SortArray(aTarget() As Long, iFirst As Integer, _
iLast As Integer, helper As ISortHelper)
Dim vSplit As Long
# ElseIf SortArrayType = 3 Then
Sub SortArray(aTarget() As String, iFirst As Integer, _
iLast As Integer, helper As ISortHelper)
Dim vSplit As String
# ElseIf SortArrayType = 4 Then
§
End Sub
This trick is so ugly and fraught with potential for error that I hesitate to include it. Still, it’s interesting to see how you can change the internal operation of a procedure simply by changing parameter and variable types. Because the default value for a conditional constant is 0, you will get the Variant version of SortArray by doing nothing. You need to define a value for SortArrayType in the Make tab of the Project Properties dialog box to get any other type. One disadvantage of this hack is that you can have only one type of SortArray per project. That’s one reason I recommend the cut-and-paste method of getting different SortArray routines over the conditional compilation method. C++
provides a feature called templates for getting around this kind of problem, but I don’t expect to see anything like this in Visual Basic for a long time—if ever.