Sort first, choosing the appropriate key for comparisons.