I'm following Karate Chop kata for a binary search. I really wanted to avoid built in functionality within the language. I'm pretty new to C# so any recommendations is greatly appreciated.
Spec: Binary chop on an int array to find the index.
A binary chop (sometimes called the more prosaic binary search) finds the position of value in a sorted array of values. It achieves some efficiency by halving the number of items under consideration each time it probes the values: in the first pass it determines whether the required value is in the top or the bottom half of the list of values. In the second pass in considers only this half, again dividing it in to two. It stops when it finds the value it is looking for, or when it runs out of array to search. Binary searches are a favorite of CS lecturers.
http://codekata.com/kata/kata02-karate-chop/
public static int Chop(int val, int[] subject)
{
// if the array count is odd
if (subject.Length % 2 != 0)
{
// if the last index is the value, we're done
if (subject[subject.Length - 1] == val)
{
return subject.Length - 1;
}
// remove the last index so that the array length is even
subject = new ArraySegment<int>(subject, 0, subject.Length - 1).ToArray();
}
// get the mid point
var mid = subject.Length / 2;
if (mid > 4)
{
int[] chopped = new int[mid];
Array.Copy(subject, chopped, mid);
if (chopped[chopped.Length - 1] > val)
{
Chop(val, chopped);
}
else
{
var segment = new ArraySegment<int>(subject, mid, subject.Length - mid);
Chop(val, segment.ToArray());
}
}
int index = -1;
for (int j = 0; j < subject.Length; j++)
{
if (val == subject[j])
{
if (index != -1)
{
duplicateIndexes.Add(index);
duplicateIndexes.Add(j);
}
index = j;
}
}
return index;
}