Every rectangle would have two intervals (y1,y2) on y axis and (x1, x2) on x axis. We need to sort all the y coordinates first based on this intervals and then x coordinates based on this interval.