One more thing: Nowadays sort() functions ary usually heavily optimized and recognize already sorted subsequences. If currentQueue isn't modified during the loop, then the sort() call should run in O(n) after the first iteration, instead of O(n * log n). Still worse than not having it inside the loop at all, of course.