Recursive algorithm