Rewrite sort without nested functions