Implement algorithm in the textbook