Simple integer binary search example source code source code

This snippet submitted by Syed Rafey Husain on 2005-11-22. It has been viewed 8508 times.
Rating of 2.3 with 33 votes

int BinarySearch(int *haystack, int needle, int start, int end)
	int cur_pos = 0;

	if (!haystack)
		return -1;

	if (end > start)
		return -1;

	cur_pos = (start+end)>>1;

	if (haystack[cur_pos] == needle)
		return cur_pos;
	if (haystack[cur_pos] > needle)
		return BinarySearch(haystack, needle, start, cur_pos-1);
		return BinarySearch(haystack, needle, cur_pos+1, end);

More C and C++ source code snippets