Here's my attempt at a binary search algorithm:
int[] intArr = new int[11] { 0, 5, 13, 19, 22, 41, 55, 68, 72, 81, 98 };
int search = 55;
bool found = false;
while (!found)
{
// if array is of length 1, and number does not equal search value, break
if (intArr.Length == 1 && intArr[0] != search)
break;
// if the midpoint number of the array is less than that you are searching for
else if (intArr[(int)Math.Round((decimal)intArr.Length / 2, MidpointRounding.AwayFromZero) - 1] < search)
// return the latter half of the remaining array
intArr = intArr.Skip((int)Math.Round((decimal)intArr.Length / 2)).ToArray();
// if the midpoint number of the array greater than that you are searching for
else if (intArr[(int)Math.Round((decimal)intArr.Length / 2, MidpointRounding.AwayFromZero) - 1] > search)
// return the former half of the remaining array
intArr = intArr.Take((int)Math.Round((decimal)intArr.Length / 2, MidpointRounding.AwayFromZero)).ToArray();
else
found = true;
}
if (found)
Console.WriteLine("Search number is: {0}",
intArr[(int)Math.Round((decimal)intArr.Length / 2) - 1]);
else
Console.WriteLine("Number not found in collection");
Console.ReadLine();
What can I do to speed-up/optimise my implementation? Testing it against the internal BinarySearch method, mine was 90 times slower!
Edit
It was pointed out that I hadn't included handling for search values not contained within the array. I've since added that, trying to conform to my original thought process. I will add the other suggested optimizations later and post the full refactored code.
int search = 50;
? \$\endgroup\$