C# Algorithms – Calculation of Squared Root with Binary Search

Binary sorting is something trivial in algorithms – it is trivial, because a lot of people know how to do it, but because even those who claim to be the professors in algorithms and be the wise guys in the area are not able to write it flawlessly. Thus, there was a bug in java.util.Arrays, because someone did not want to test what happens when you search with big values.2622a2352f28875c4a625b038f86b49f

Anyhow, in the current article I will present my algorithm for calculation of squared root with a binary search. It is definitely not the best one, but it works somehow:


binarySorting

 

 

So what do I do? Simply I define a precision that I want to achieve and in my case it is 0.00001 and I start a binary search to go find the best mid, which fits the following:

Once it is found, I simply display it and round the number to 5 digits after the comma. That is all folks. Here comes the code:

With the special support of C# in Linux! (probably I am the only blogger in the world blogging for C# in Mint and Ubuntu, but I like it… somehow).

c#

Tagged with: , ,