Algorithms - Implement Binary Search

My code passes in all tests except for the last one:

The result the lesson expects from the last test, while having the provided test array and the number 70 as arguments to my function, is [ 13, 19, 22, 49, 70 ] . However, in spite of my code succeeding in all previous tests, it fails the last one by returning [13, 19, 22, 23, 49, 70].

It just doesn’t make sense to me. I understand how my code works, but I can’t figure out a way to have the code pass the last test while simultaneously succeeding in the previous ones; when I alter the logic to yield the expected result, the function won’t comply with the criteria necessary to pass all tests.

   **Your code so far**
function binarySearch(arr, value)
{
	const path = [];

	return (function _binarySearch(arr, value)
	{
		if (arr.length < 2)
		{
			const target = arr[0];
			return target === value ? path.concat(target) : 'Value Not Found';
		}
		const i = Math.floor(arr.length / 2);
		const left = arr.slice(0, i);
		const right = arr.slice(i);
		const target = left[left.length - 1];

		path.push(target);

		if (target === value) return path;

		return _binarySearch(target < value ? right : left, value);
	})
	(arr, value);
}

Challenge: Algorithms - Implement Binary Search

Link to the challenge:

You are including the middle value in your right array.

Also, you are computing the middle index a bit differently than the solution expects. For an array of length 3, the middle index is at 1. For an array of length 4, the middle index is also at 1.


Fixing those two things, your code passes for me.

I’d look at the solution in the Guide for this one - all that extra copying and the recursion is inefficient and doesn’t really help you in this case.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.