I am trying to solve this question, but I am stuck on how to make this work. I will post the question, and then explain where I am in it.
Given a set of horizontal line segments and vertical lines of total size n, we want to compute the number of horizontal segments intersected by each vertical line. The algorithm should be of complexity O(n*logn), and should be achieved by sorting, following by a linear scan. A horizontal segment is specified by two x-coordinates and a y-coordinate, while a vertical line is specified by a single x-coordinate. Output is an array of numbers count[l], one for each vertical line l.
For the sorting, I would think I would sort the entire set by which line finishes earliest (i.e. smallest second x-coordinate, or in the case of a vertical line, just its one x-coordinate) so that I have a linear progression through all of the lines. I am just confused as to how the linear scan following the sorting should be played out. If anyone has any hints, tips, or guidelines, I would appreciate it!
PS: This is practise for a midterm, so while it’s not necessarily homework, I will still mark it as such.
The question can be written otherwise:
Foreach horizontal segment (x1,x2), find all the vertical lines that intersect it. You can do that by sorting the vertical lines getting a set of position x.
Now, run a binary search and position x1 in the set of x’s, let’s call its position p1. Do the same for x2, p2. The number of intersection for the given segment equals p2-p1.
Do that for all the horizontal segements.
Sorting the vertical segments will take O(klog(k)). Every search is done in O(log(k)) and is done twice for each segment: O(mlog(k)). Where k is the number of vertical lines and m the number of horizontal segments. n = m+k > m,k therefor, the overall complexity is O(nlogn).