I wrote the comment before the parent made their edit so the logic did match what it was at the time.
Having said that it would've been a very simple extension to make it a recursive algorithm which includes the else case, and arguably would be clearer than the for loop solution.