ex18: Refactor to array iteration

Reduces code duplication and makes it easier to add more sorting and
comparison functions.