moving sort function out of loop