Binary Search

Binary search (a.k.a Half-Interval Search) algorithms finds the position of a target value within an array.



									public static int BinarySearch(int[] data, int value)
{
	int low = 0, high = data.Length - 1, midpoint = 0;

	while (low <= high)
	{
		midpoint = low + (high - low) / 2;

		if (value == data[midpoint])
			return midpoint;
		else if (value < data[midpoint])
			high = midpoint - 1;
		else
			low = midpoint + 1;
	}

	return -1;
}
								


Example

									int[] data = new int[10];
for (int i = 0; i < 10; i++)
{
	data[i] = i * 10;
}

int value = BinarySearch(data, 60);
								


Output

									6