what to say... you can try to find an algorithm yourself, which is challenging if you don't already know the answer, or you can go to the web and get the algorithm and then code it.
at a glance your algorithm appears to be N*N, while ... for ...
All I will tell you for now is that the algorithm is far better than N*N run time. So the answer is, find a better method.