On 2/27/19 1:33 AM, Wolfgang Kilian wrote:
> At present, this is not possible. The difficult part is the 'different
> types are covered' bit. It is straightforward to implement algorithms
> for the finite set of intrinsic types (others have pointed to examples).
> A satisfactory solution that supports any (derived) type, without
> major inconveniences for the user, is not possible within the scope of
> present Fortran.
There is a straightforward way to achieve this goal in current fortran
(or f90, or f77 for that matter) for the requested task and for similar
sorting and ordering tasks.
The general approach is that the sort/ordering program always works with
the integer indexing array. One argument to the sort routine is a dummy
function, written by the programmer, that returns the result of
comparisons between two array elements given their integer indices. The
sort routine never needs to see or declare the user defined type that is
being compared, so there is no problem with allowing it to work on any
intrinsic or user defined type. Also, elements of those derived types
are never copied or swapped, it is only the elements of the integer
index array that are swapped. This is a nice feature of this approach
for complicated derived types that have, for example, big memory
footprints or allocatable members of arbitrary size. This approach also
works well when arbitrary subsets of the underlying data are sorted.
I remember a similar discussion to this a few years ago here in CLF, and
I think I posted an example of a heap sort that worked this way. If what
I'm explaining isn't obvious, I can try to dig out that routine and
repost it. I personally like heap sort over the other alternatives for
these kinds of sorting tasks. It sorts in-place with no extra memory
requirements, it is O(N*log(N)) scaling, and that is also its worst-case
behavior. Also, heap sort is easy to understand and implement in
fortran, it can be done with loops rather than recursion, and so on.
A previous post referred to a library that was mostly based on merge
sorts. Merge sorts are also easy to understand and implement in fortran,
but they are not in-place, they require intermediate work arrays. Qsort
was also mentioned. Its downside is that its worst case behavior is N^2
rather than N*log(N). And someone also posted a brute force N^2
selection sort, which is easy to implement, but has no place in an
efficient library of sort and order routines. There are special
situations in which all of those algorithms are appropriate, of course,
but heap sort is a nice general purpose approach particularly when used
with an index vector to order arbitrary elements of arbitrary types.
$.02 -Ron Shepard