Product SiteDocumentation Site

5.3.18. Sorting Ordered Collections

Any ordered collection, such as non-sparse Arrays or Lists can have its elements placed into sorted order using the sort method. The simplest sort is sorting an array of strings.

Example 5.175. Array class - sorting

myArray = .array~of("Zoe", "Fred", "Xavier", "Andy")
myArray~sort

do name over myArray
   say name
end

will display the names in the order "Andy", "Fred", "Xavier", "Zoe".
The sort method orders the strings by using the compareTo method of the String class. The compareTo method knows how to compare one string to another, and returns the values -1 (less than), 0 (equal), or 1 (greater than) to indicate the relative ordering of the two strings.

5.3.18.1. Sorting non-strings

Sorting is not limited to string values. Any object that inherits the Comparable mixin class and implements a compareTo method can be sorted. The DateTime class (Section 5.4.1, “The DateTime Class”) and TimeSpan class (Section 5.4.3, “The TimeSpan Class”) are examples of built-in Rexx classes that can be sorted. Any user created class may also implement a compareTo() method to enable sorting. For example, consider the following simple class:

Example 5.176. Non-string sorting


  ::class Employee inherit Comparable

  ::attribute id
  ::attribute name

  ::method init
    expose id name
    use arg id, name

  ::method compareTo
    expose id
  	use arg other
    return id~compareTo(other~id) -- comparison performed using employee id

  ::method string
    expose name
    return "Employee" name




The Employee class implements its sort order using the employee identification number. When the sort method needs to compare two Employee instances, it will call the compareTo method on one of the instances, passing the second instance as an argument. The compareTo method tells the sort method which of the two instances should be first.

Example 5.177. Comparison during sorting


    a = .array~new
    a[1] = .Employee~new(654321, "Fred")
    a[2] = .Employee~new(123456, "George")
    a[3] = .Employee~new(333333, "William")

    a~sort

    do employee over a
       say employee    -- sorted order is "George", "William", "Fred"
    end