You need to read a little bit more about collision detection as I am sure there is better way to do it then your way. I am sure that there are developed algorithms and you just pick the one that suits your needs.
Just google it.
Cheers and good luck with the code.