japhy++ for the right explanation. I just want to add that when you get strange behaviour, your first thought should be to alter your test case. Generate other sequences. Use rand(). Try to see when it behaves the way you expect it to, or don't.
No shame.. everyone makes boneheaded mistakes. It took me a couple of those before I understood that same advice I just gave you, and I sometimes still have to remind myself that it may only be a coincidence with the chosen test case.
Pragmatic lesson I took home: when testing code, generate two random and reasonably large test cases to run it against. Even if one of the data sets happens to display strange behaviour, odds that they both do in the same way are rather low.