Sort, why only certain types?

Since Xojo makes >, >=, <, <= and = call the instance’s Operator_Compare, why can ary.Sort not work on any class implementing Operator_Compare?

The short answer is that it’s hard to do at runtime.

The long answer is that Operator_Compare can be overloaded to take a bunch of different types. The runtime would have to do overload resolution and type conversion logic – essentially doing work that, currently, only the compiler knows how to do. Assuming that was a non-issue, it’s also possible that there simply just isn’t enough information to do it at runtime. I don’t recall all of the details.

The way to do it is to implement a class interface “Sortable” (or something) that declares the method “SortValue() As String”. Put the following Sort method into a module:

Sub Sort(Extends arr() As Sortable)
  dim sortArr() as string
  redim sortArr( arr.Ubound )
  for i as integer = 0 to arr.Ubound
    sortArr( i ) = arr( i ).SortValue
  next i
  sortArr.SortWith( arr )
End Sub

Make your class a “Sortable”, implement SortValue in the right way, and you can sort.

(I chose String as the return for SortValue because it’s the most flexible type that will work with SortWith.)

An interface is definitely a great approach to the problem. You could implement quicksort or something yourself in Xojo code and have the sortable return an integer saying its relation to the object passed in. It’d avoid conversions to string and may end up being faster.

Yes, you could implement Operator_Compare in the Interface instead of SortValue, and your implementation of the Operator_Compare(value As Sortable) As Integer method could convert the given object to the native class first, then do the comparison.

But I think the overhead of the Xojo-based QuickSort on a large array would make it slower than using SortWith even with the conversion to string.

Seems some benchmarking is in order :slight_smile:

Definitely the best approach to any performance problem. The string approach requires at least one call to malloc and then comparing the strings case insensitively – neither of which are free.

As for having Operator_Compare be in the interface, this means that you lose a fair amount of type safety at compile time. The compiler would allow your objects to be compared to any other objects that implement the interface.