R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

Binary Search

The Question

Given a sorted array of numbers, locate the index of a specified value by using the following algorithm.

1. Identify the middle number in the array

2. Determine if the desired value is higher, lower, or equal to the middle number

3. If it is equal, you are finished.

4. If not, repeat these steps, using only half of the previous set of numbers, until you locate the desired value. 

Approach

Array =  [1, 3, 4, 7, 12, 17, 20, 30, 31, 35, 40, 90]

Desired value = 20

1.   Select middle:    [1, 3, 4, 7, 12, 17, 20, 30, 31, 35, 40, 90]

2.   20 > 17 : Reduce array:

3.   Select middle: 

4.   20 < 31 : Reduce array:

5.   Select middle:

6.   20 = 20  :  Return 6, the index of 20 from the original array. 

[1, 3, 4, 7, 12, 17,

 20, 30, 31, 35, 40, 90]

[1, 3, 4, 7, 12, 17,

 20, 30, 31, 35, 40, 90]

[1, 3, 4, 7, 12, 17,

, 31, 35, 40, 90]

20, 30

[1, 3, 4, 7, 12, 17,

20, 30

, 31, 35, 40, 90]

Solution 1 - Iterative

// Set start and end to 0 and array.length - 1
function binarySearch(array, value){
        
        var start = 0;
        var end = array.length-1

	while (start <= end){

		var midIndex = Math.floor((start + end) / 2);
		var midValue = array[midIndex];

		if (midValue === value){
			return midIndex;
		}
		else if (midValue < value){
			start = midIndex+1;
		}
		else {
			end = midIndex-1;
		}
	}
	return -1;
};

Solution 2 - Recursive

// Set start and end to 0 and array.length - 1
function binarySearch(array, value, start, end) {

	// If the value is not in the array, return -1
  	if (start > end) { return -1; }

  	var midIndex = Math.floor((start + end) / 2);
  	var midValue = array[midIndex];

  	if (value < midValue) { 
  		return binarySearch(array, value, start, midIndex-1); 
  	};

  	if (value > midValue) { 
  		return binarySearch(array, value, midIndex+1, end); 
  	};

  	// If value is equal to the middle value
  	return midIndex;
}

Complexity  - O(log N)

If N is the size of the array, then the number of comparisons that are performed during the search is roughly log(N). 

 

At each step, the number of possible values is halved. Therefore the total (most) number of steps will be log(N). 

The End

Binary Search

By Ivan Loughman-Pawelko

Binary Search

Technical interview problem on binary search

  • 1,530