private void merge(int mergeAt, Range range) {
ranges.add(mergeAt, range);
if (mergeAt > 0) {
Range beforeMerge = ranges.get(mergeAt - 1);
if (range.isTouching(beforeMerge)) {
ranges.remove(mergeAt);
beforeMerge.end = Math.max(beforeMerge.end, range.end);
mergeAt--;
range = ranges.get(mergeAt);
}
}
if (mergeAt + 1 < length()) {
Range afterMerge = ranges.get(mergeAt + 1);
while (mergeAt < length() - 1 && range.isTouching(afterMerge)) {
range.start = Math.min(range.start, afterMerge.start);
range.end = Math.max(range.end, afterMerge.end);
ranges.remove(mergeAt + 1);
if (mergeAt + 1 < length())