Added ensureSorted for optimization. Not tested.