Add nested loop for sorting