Finished algorithm for lab 4 task 3