Skip over navigation

Binary Search

Problems

Binary Search as Applied to Arrays

How to Cite This SparkNote

Problem : Why would happen if binary search were called on an unsorted array?

It wouldn't work (unless by fluke). It would look at the middle element to make a decision as to which half to discard, but since the array is not sorted the decision will be erroneous.

Problem : Does the middle pointer necessarily have to be given the value (first + last) / 2, or could it be any value in between first and last?

It could be any value in between and the algorithm will still work. However, the algorithm's efficiency will decrease the further away from the middle we go.

Problem : theSpark.com stores their user database in a big array, sorted alphabetically by user name. The array contains 2.5 million elements. How many comparisons, at most, will it take their binary search algorithm to locate the data it is searching for?

It will take at most 22 comparisons; ceil (log(2, 500, 000)) = = 22 .

Problem : If you were to be doing many searches on a sorted linked list of n elements, how might you transform the list to increase the efficiency in the long run?

Transform the linked list into an array. This will take O(n) time. However, subsequent searches will take only O(logn) instead of O(n) .

Problem : Someone gives you an array of integers sorted in descending order. Rewrite the binary search code to account for this.


int binary_search(int arr[], int find, int first, int last)
{
	int middle, found;

	found = 0;
	while((first <= last) && !found) {
		middle = (first + last) / 2;
		if (arr[middle] == find) found = 1; 
		else if (arr[middle] < find) last = middle - 1;
		else first = middle + 1;
	}

	if (found) return middle;
	else return -1;
}

Follow Us