Tom Shelton
7/31/2011 10:21:00 PM
MM explained on 7/31/2011 :
> Let's suppose I have a Sort procedure and I pass it a UDT, such as:
>
> Type MyType
> Dog As String
> Cat As String
> End Type
>
> Public Pets() as MyType
>
> Redim... as required...
>
> Call the Sort proc:
>
> QuickSort Pets(), lo, hi, "Dog"
>
> This will tell the Sort proc to do the comparions using the Dog field.
> Alternatively, QuickSort Pets(), lo, hi, "Cat" would target the Cat
> field.
>
> Possible?
>
> If not a named field, then what about passing a number, e.g. 1 or 2:
> QuickSort Pets(), lo, hi, 1
>
> or
>
> QuickSort Pets(), lo, hi, 2
>
> where 1 signifies Dog and 2 signifies Cat for the comparisons.
>
> MM
The real issue is the compare routine. Most modern languages would let
you basically pass in the equivalent of a funciton pointer to use as
the comparison (usually, this function would return a -1, 0, 1). In
vb, you could do something similar - using api's etc, but an easier way
would be to use an object for your type and interfaces (well, you can
use a udt, if you define it in a public class module - but for this
example, I'm going to change it to a class). Something like (remember,
this is dummy code - so, it does not reflect best practices):
' CMyType
Public Dog As String
Public Cat As String
That's our type. Now your QuickSort might should change it's last
parameter to be something like IComparer. This interface might look
like:
' IComparer interface.
Public Function Compare(lhs As Object, rhs As Object) As Integer
' no op...
End Function
Now, you could create a comparer for dogs:
' Simple Dog Comparer
Implements IComparer
Private Function IComparer_Compare(lhs As Object, rhs As Object) As
Integer
Dim a As MyType
Dim b As MyType
Set a = lhs
Set b = rhs
Select Case a.Dog
Case Is > b.Dog
IComparer_Compare = 1
Case Is < b.Dog
IComparer_Compare = -1
End Select
End Function
Then, if you want to compare dogs, you can do something like:
Dim dc as IComparer
Set dc = New SimpleDogComparer
QuickSort Pets(), lo, hi, dc
Then you just modify your quicksort routine to sort based on the return
of IComparer.Compare
This way, you keep your quicksort algorithm generic, and decoupled from
any specific type of data. You let the caller define the actual
relative value comparison.
--
Tom Shelton