modified to use sorted()