Search code examples
collectionscomparableeiffel

Some ways to sort a collection of comparables in eiffel


Which library of the kernel should I use to sort a collection in eiffel?

where can I find an example of sort? are the tipical bubble sort, etc available?

Any sorter with agent would be very useful too to avoid having to do it with a comparable which is not implemented for example with PATH class


Solution

  • Library base_extension provides a deferred class SORTER with effective implementations of bubble, quick and shell sort algorithms.

    It uses a comparator object to do the comparison on elements of an arbitrary type, not necessarily of type COMPARABLE. One of implementations of the comparator interface is AGENT_EQUALITY_TESTER to which you pass an agent to determine whether one object is less than another one.

    Here is an example how paths can be sorted by their canonical name using bubble sort:

    sort_paths (a_paths: INDEXABLE [PATH, INTEGER])
        local
            l_sorter: SORTER [PATH]
        do
            create {BUBBLE_SORTER [PATH]} l_sorter.make
                (create {AGENT_EQUALITY_TESTER [PATH]}.make (
                    agent (a_p1, a_p2: PATH): BOOLEAN
                        do
                            Result := a_p1.canonical_path < a_p2.canonical_path
                        end))
            l_sorter.sort (a_paths)
        end
    

    Now, if there is a list of paths paths of type ARRAYED_LIST [PATH], it can be sorted by calling sort_paths (paths).