This Kata requires you to implement 5 different ways of performing a binarychop/search algorithm on an array of integers. I have chosen to do this in Apex (the Force.com language) as a way to improve my Apex skills but also to show how Apex can be used the same as any other language.
The method I have chosen to use today (the other parts will come daily) is what I consider to be the obvious way of doing it, having my search position until I have found the correct position and returning that, or returning a failure when I have no further searching position. The code is as follows below:
public Integer BinaryChop(Integer target, Integer[] searchArr)
{
Integer targetSpot = (searchArr.size()-1)/2;
Integer oldSpot = 0;
while(oldSpot != targetSpot)
{
oldSpot = targetSpot;
if(searchArr[targetSpot] > target) {
targetSpot -= (searchArr.size() - 1 - targetSpot)/2;
} else if(searchArr[targetSpot] < target) {
targetSpot += targetSpot/2;
} else if(searchArr[targetSpot] = target) {
return targetSpot;
}
}
return -1;
}
I found this an interesting exercise to perform and look forward to finding a new way of doing it tomorrow. Either way I have learnt that I need to improve my breadth of general algorithmic knowledge.