finished nearest merger algorithm