The algorithm in my mind would terminate. However, I am not sure about the complexity. I will give it more thoughts when I get time. Nice problem!