There's a rule in computing: Don't re-invent the wheel. So please take a look at Algorithm 463 from the Collected Algorithms of the Association for Computing Machinery: https://calgo.acm.org/