- and
- and
Firstly note that can be sorted to . For any , let us denote the element in that forms a line with by , consider the tuple formed by , let us denote this tuple as , this is done so that for any index we note that forms a line with for
We remark that if happened to be sorted then there would be no crossings, this follows by the definition of a crossing. The dual of this situation is when we have being indices into wherein , the lines and must cross, this holds true because was sorted, which means that if then we have .
Observe that in the above remark, we've noted that for every instance of such that , we get exactly one line crossing between the two lines being defined. Therefore we've reduced this problem to counting the number of inversions in .
Since we have an algorithm that we have proven correct as well as showing that it's time complexity is , we are able to conclude that by passing to count_inversions
we know that this extended algorithm correctly returns the number of inversions in .
We also observe that the number of line crossings between and is exactly equal to the number of line crossings between and , this can be seen because even though the order in which the points are observed has changed, the actual points included in the two sets doesn't, therefore the realize the same situation, so counting crossings in one yields the same answer as counting crossings in the other.
We've proven that our algorithm is correct, we now turn to the time analysis.
Therefore the total runtime is
def count_line_crossings(P, Q): l = line_map(P, Q) P_s = sort(P) Q_prime = map(l, P_s) return count_inversions(Q_prime)
Note that line map can be thought of as a function which takes a point in P and takes it to it's corresponding point in Q it is connected to.