Implementing Binary Search of an Array
Explore how binary search works on sorted arrays by understanding its step-by-step process and pseudocode. Learn to implement a binary search function that efficiently finds target values or determines if they are absent.
We'll cover the following...
Let's think about binary search on a sorted array. Many programming languages already provide methods for determining whether a given element is in an array and, if it is, its location. But we want to implement it ourselves, to understand how you can implement such methods. Here's an array of the first 25 prime numbers, in order:
Suppose we want to know whether the number
We might also want to know how many primes are smaller than
The position of an element in an array is known as its index. Array indices start at
Looking at the example below, we can read the array of prime numbers from left to right, one at a time, until we find the number
Once we know that the prime number
Did you see how many steps that took? A binary search might be more efficient. Because the array of prime numbers contains 25 numbers, the indices into the array range from
Is the index we are looking for higher or lower than
What's the next index to guess? The average of
The binary search algorithm stops at this point, since it has found the answer. It took only two guesses, instead of the 19 guesses that linear search would have taken. You can step through that again in the visualization below:
Pseudocode
We just described the binary search algorithm in English, stepping through one example. That's one way to do it, but a human language explanation can vary in quality. It can be too short or too long, and—most importantly—it's not always as precise as it should be. We could jump to showing you binary search in a programming language like JavaScript or Python, but programs contain lots of details due to requirements imposed by the programming language and because programs have to handle errors caused by bad data, user error, or system faults. These details can make it hard to understand the underlying algorithm from studying just the code. That's why we prefer to describe algorithms in something called pseudocode, which mixes English with features that you see in programming languages.
Below is the pseudocode for binary search, modified for searching in an array. The inputs are the array, which we call array; the number
Let min = 0 and max=n − 1.
Compute guess as the average of max and min, rounded down so that it is an integer.
If array[guess] equals target, then stop. You found it! Return guess.
If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
Otherwise, the guess was too high. Set max = guess - 1.
Go back to step two.
Implementing Pseudocode
We'll alternate between English, pseudocode, and an actual programming language like Javascript or Python in these tutorials, depending on the situation. As a programmer, you should learn to understand pseudocode and be able to turn it into your language of choice. Even though we're using JavaScript here, it should be straightforward for you to implement pseudocode using other languages.
How would we turn the pseudocode in the example above into a JavaScript/Python program? We should create a function because we're writing code that accepts an input and returns an output, and we want that code to be reusable for different inputs. The parameters to the function—let's call it binarySearch—will be the array and target value, and the return value of the function will be the index of the location where the target value was found.
Now let's go into the body of the function and decide how to implement our plan. Step six says to go back to step two. That sounds like a loop. Should it be a for-loop or a while-loop? If you really wanted to use a for-loop, you could, but the indices guessed by binary search don't go in the sequential order that would make a for-loop convenient. We might first guess the index
There's also an important step missing in the pseudocode that doesn't matter for the guessing game, but does matter for the binary search of an array. What would happen if the number you are looking for is not in the array? Let's start by figuring out what index the binarySearch function should return in this case. It should be a number that cannot be a legal index into the array. We'll use
The target number isn't in the array if there are no possible guesses left. In our example, suppose that we're searching for the target number
Here is modified pseudocode for binary search that handles the case in which the target number is not present:
Let min = 0 and max = n − 1.
If max<min, then stop; target is not present in array. Return -1.
Compute guess as the average of max and min, rounded down so that it is an integer.
If array[guess] equals target, then stop. You found it! Return guess.
If the guess was too low, that is, array[guess] < target, then set min = guess + 1.
Otherwise, the guess was too high. Set max = guess - 1.
Go back to step two.
Now that we've thought through the pseudocode together, try implementing binary search yourself. It's fine to look back at the pseudocode. In fact, it's a good thing because then you'll have a better grasp of what it means to convert pseudocode into a program.