second version with queue and sort