use the sorted flag to decide about sorting