Code for the search-and-copy algorithm