Rewrite sorting code