Proofs: Interval merging by sorting
These are the human proofs of Interval merging by sorting, at full length.
Interval merging by sorting returns the components of the union full
This proof shows: correctness, termination.
We use the pseudocode of the page. Let be the intervals in the order that line L1 makes, so . Let , with , and let .
Claim. For closed intervals, MERGE-INTERVALS returns the list of the connected components of , sorted from left to right. With the test in line L4, it does the same for open intervals with ; with the test of the page, it does the same for half-open intervals with .
Proof for closed intervals. We prove this invariant of the loop of line L3.
(I) After steps, with : is the list of the components of , sorted, and if then the last component is with .
Each component of a finite union of closed intervals is a closed interval, because it is the union of the finitely many input intervals that lie in it, and a finite union of closed intervals that is connected is a closed interval.
Initialization. With , line L2 makes empty, and has no components.
Maintenance. Assume (I) after steps, , and let .
- If is empty, then , line L5 makes , and is the only component of . Also and .
- If , line L5 appends . Each point of is at most , so the open gap is not in , and is the disjoint union of and with this gap between them. So the components of are and , in this order. Also , since , and the new last component starts at .
- If , line L6 sets the right end of to . By (I) and the sort, , so and meets . Hence is an interval. For , the component ends before with a gap, because and are different components of and is to the left. Since starts at , it does not reach or the gap after it. So the components of are and , and .
In each case (I) holds after steps.
Termination. The loop of line L3 runs exactly times, once for each interval, because each step consumes one element of the finite sorted list. After the last step, (I) with says that is the sorted list of the components of , and line L7 returns it.
Half-open intervals. For with , replace closed by half-open in (I) and let . In case 2, leaves the nonempty gap uncovered. In case 3, gives , an interval, also when : the point is in because . The rest of the proof is the same.
Open intervals. For with and line L4 changed to , let . In case 2, now , and the point is in no interval (each ends at most at and excludes its end) and not in , since . So the components are separated, and the new one is . In case 3, now , and is an interval because and the two open intervals share the points just above . The rest is the same.
Cost. Line L1 sorts items. Each of the steps of the loop does one comparison in line L4, at most one maximum in line L6, and other work, so the scan costs time.