Sorting before printing to preserve order