You could do this in linear time without the sort(), but in practice the array size will be small enough that it shouldn't matter.