static void Main(string[] args)
{
int[] arrayList = { 45, 36, 77, 12, -98, 0, 6, 22, 32, -3 };
int[] sortedArrayList = { -98, -3, 0, 6, 12, 22, 32, 36, 45, 77};
int[] searchElement = { 45, -3, 12, 102, -102, 15 };
int position, i;
for (int pos = 0; pos < searchElement.Length; pos++)
{
position = LinearSearch(arrayList, searchElement[pos], out i);
if (position == -1)
Console.WriteLine("{0} is not in ArrayList.{1}", searchElement[pos], i);
else
Console.WriteLine("{0} is at position {1} in ArrayList", searchElement[pos],
position);
}
for (int pos = 0; pos < searchElement.Length; pos++)
{
position = BetterLinearSearch(sortedArrayList, searchElement[pos], out i);
if (position == -1)
Console.WriteLine("{0} is not in sortedArrayList.{1}", searchElement[pos], i);
else
Console.WriteLine("{0} is at position {1} in sortedArrayList", searchElement[pos],
position);
}
}
// BinarySearch method
static int MyBinarySearch(int[] keys, int v) {
int position = -1;
int begin = 0, end = keys.Length - 1;
bool found = false;
while ((begin <= end) && !found) {
position = (begin + end) / 2;
if (keys[position] == v)
found = true; // just right
else if (keys[position] < v)
begin = position + 1; // too small
else
end = position - 1; // too big
}
if (found)
return position;
else
return -1;
}