change to recursive algorithm