Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
java
c++
python
community creator

How to do an iterative binary search in multiple languages

Tarun Telang

A binary search algorithm searches for a specific item in a sorted collection with specific left and right indices. If the collection is unordered, we need to sort it before applying a binary search. The sorted collectionalso known as the search space is divided into two halves after every comparison. Hence, the algorithm runs with a logarithmic time complexity of O(log(n))O(log(n)).

Binary search returns the item’s index location in the collection if the search succeeds; otherwise, it returns the appropriate error messages or values.

Code

Below is the code used in multiple languagesi.e., JavaScript, Python, and C++ to perform a binary search on an array using iterative implementation:

// function to perform binary search 
const binarySearch = (array, target) =>  {
	if (array == null || array.length == 0)
		return -1;
		
	let left = 0; // left boundary of search space
	let right = array.length - 1; // right boundary of search space
	while (left <= right) { 
		// index used in determining whether to search left or right.
		let middle = Math.floor((left + right)/2);
		if (target === array[middle]){
			return middle;
		} else if (target < array[middle]) {
			right = middle - 1;
		} else {
			left = middle + 1;
		}
	}
	return -1; 
}

// array - collection to be searched. 
let array= [2, 4, 5, 6, 7, 8, 23, 34, 54, 56]; 

// target - value to be searched
let target = 8; 

console.log(binarySearch(array, target)); 
// returns 5, the index of the target in the array. 

target = 9; // now searching for 9
console.log(binarySearch(array, target)); // returns -1

RELATED TAGS

javascript
java
c++
python
community creator
RELATED COURSES

View all Courses

Keep Exploring