added flag to sort function to make less computations