Binary Search

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



									static int BinarySearch(int data[], int count, int value) {
	int low = 0, high = count - 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 (size_t i = 0; i < 10; i++)
{
	data[i] = i * 10;
}

int value = BinarySearch(data, 10, 60);
								


Output

									6