Line array, connect lines at the end

I want to get into this situation

image

how coul I archive this?

in this specific case, but not in the generic case

  1. get all points of all lines in a datastructure, like a nested list
  2. sort the lines with respect to the y-coordinate of the points
  3. direction of the lines should head towards x-axis
  4. connect start of line i and start of line i+1, connect end of line i+1 with end of line i+2, loop over all expect the two last lines