Quick revision
The short answer
Searching a sorted array is the classic binary search. We keep a range from lo to hi, compare the target with the middle element, and throw away the half that cannot hold it, so the range halves every step. It takes O(log n) time and O(1) extra space.
The solution
What it costs
| Approach | Time | Extra space | Needs sorted input? |
|---|---|---|---|
| Linear scan from the left | O(n) | O(1) | no |
| Build a hash set, then look up | O(n) to build, then O(1) | O(n) | no, and it gives no index |
| Binary search | O(log n) | O(1) | yes |
What to remember
We searched a sorted array by keeping a range from lo to hi, comparing the target with the middle element, and moving lo to mid + 1 or hi to mid - 1 so that the half which cannot hold the target is thrown away. The loop runs while lo <= hi and returns -1 when the range is empty. It costs O(log n) time and O(1) space. The clue to remember is the word sorted: when one comparison can rule out a whole side, look in the middle and halve.
1What it means to search a sorted array
Think of looking up a word in a thick paper dictionary. Nobody starts at the first page and reads every word until they reach the right one. You open the book somewhere near the middle, glance at the words on that page, and see at once whether your word comes before them or after them. If it comes before, the whole second half of the book is no longer your concern. You open the remaining part near its middle and decide again, and in a handful of moves you are on the right page. You can do this only because the words are in alphabetical order.
Binary search is that habit written as a program. We are given an array, a row of numbers stored side by side, whose values are sorted from smallest to largest, and a number called the target. We must return the position of the target in the array, called its index, or -1 if the target is not there. In Java the first position has index 0. The problem is much smaller than it looks, because the method is only three choices repeated: look in the middle, compare, and throw away the half that cannot hold the answer.
Let us keep one example for the whole article. The array is 2, 5, 8, 12, 16, 23, 38, 56, 72, 91, ten numbers at indexes 0 to 9, and the target is 23. Looking at it, you can see 23 sits at index 5, so the answer is 5. The picture marks it.
Ten sorted numbers with their indexes above them. The answer is the index of 23.
- target
- 23
- answer
- 5
1The array holds ten numbers sorted from smallest to largest. The target 23 is at index 5, so the method should return 5.
What to assume
- Is the array really sorted, and in increasing order?
- We assume yes.
- What should we return when the target is missing?
- We return -1, since no real index is negative.
- What if the target appears more than once?
- We return any one of its positions, and an interviewer who wants the first one will say so.
- And can the array be empty?
- Yes, and then the answer is -1.
A careful candidate asks a few questions before writing code. Is the array really sorted, and in increasing order? We assume yes, because the whole method depends on it. What should we return when the target is missing? We return -1, since no real index is negative. What if the target appears more than once? We return any one of its positions, and an interviewer who wants the first one will say so. And can the array be empty? Yes, and then the answer is -1.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a binary search problem
A beginner reading this question usually thinks first of a loop that checks every number from the left until it finds the target. It is correct, and we will try it next. But notice that this loop would work just as well on a jumbled array. It never uses the fact that the numbers are in order, and that fact is the most important word in the question.
So let us read the question slowly and take the clues one at a time. The first clue is the word sorted. In a sorted array, a single comparison tells us about many numbers at once. If the number at some index is smaller than the target, then every number to its left is smaller still, so none of them can be the target. One look rules out a whole group of positions, just as one glance at a dictionary page rules out half the book.
The second clue is the word search, for one number. We are not asked to change the array or to look at all of it, only to find one place. When a question asks for one place in ordered data, the question to ask yourself is how much each comparison can throw away. If one comparison can throw away half, we only need a few comparisons.
These clues point to the binary search pattern. Binary means having two parts, and the name describes the method. At every step we cut the part of the array still in play into two halves around its middle and keep only the half that can still hold the target. The part still in play is called the search range, and we track it with two indexes, lo for its left end and hi for its right end. The rule to carry to new problems is this. When data is sorted, or when the answer to a yes or no question switches only once as a number grows, look at the middle and throw away the half that cannot hold the answer.
Some patterns look similar but do not fit as well. A hash set, a structure that can tell whether it holds a value in about one step, could answer whether 23 is present, but building it reads every number once, as the plain loop does, and it gives no index. Two pointers that move in from both ends are useful for finding pairs in a sorted array, but for a single value they still crawl one step at a time.
3The brute force, checking every number from the left
The honest first attempt is a brute force, one that tries every possibility in turn. It is correct, easy to trust, and the right answer when an array is not sorted. We check each index from the left and return as soon as the number there equals the target. If the loop finishes without finding it, we return -1.
Compared cells were checked and were not the target. The scan uses nothing about the order.
- target
- 23
- comparisons
- 6
1Searching for 23, the scan compares 2, 5, 8, 12 and 16 before it reaches 23 at index 5. That is six comparisons.
- target
- 7
- comparisons
- 10
- answer
- -1
2Searching for 7, which is missing, the scan checks all ten numbers before it can say -1, even though 8 already proved 7 is not there.
Let us count on the example. To find 23 the loop compares 2, 5, 8, 12, 16 and then 23, six comparisons. To find 91, the last number, it needs all ten. To report that 7 is missing it also needs all ten, because it cannot stop until it has looked everywhere. In general an array of n numbers needs up to n comparisons, so the time is O(n), which means the work grows in step with n. The extra space is one index variable, O(1).
So where is the waste? Look at the search for 7 in the second frame. When the loop reached 8 at index 2, it had the proof that 7 is not in the array, because every number after 8 is bigger still. It carried on anyway, checking seven more numbers it could have ruled out without looking. And searching for 23, the comparison with 16 told us that 2, 5, 8 and 12 were too small, but the loop had already spent four comparisons on them. Each comparison tells the loop about one number when, in a sorted array, it could tell us about many.
4Getting to binary search, one decision at a time
The waste tells us what to aim for. We want each comparison to rule out as many numbers as possible. Where should we look first? Comparing the target with the first number, 2, rules out exactly one position. Comparing it with 16, near the middle at index 4, does far more. If 16 is smaller than 23, then 2, 5, 8, 12 and 16 are all too small, and five positions vanish at once. If 16 were bigger, the five to its right would vanish instead. At the middle, even the worse outcome throws away half.
So we keep the search range from lo to hi, starting with the whole array, lo = 0 and hi = 9. At each step we take the middle index, mid, and compare a[mid] with the target. If they are equal, we have found it and return mid. If a[mid] is smaller than the target, the target can only be to the right of mid, so we move lo to mid + 1. If a[mid] is bigger, the target can only be to the left, so we move hi to mid - 1. Then we repeat on what is left.
Here a beginner usually asks why we move lo to mid + 1 and not simply to mid. Surely mid is close to the answer? Let us try it and see what goes wrong. Suppose the range has shrunk to lo = 5 and hi = 6 and the target is 38, at index 6. The middle is 5, and a[5] is 23, smaller than 38. If we set lo = mid, lo stays at 5, the middle is 5 again, and the loop asks the same question forever. We already know a[mid] is not the target, so mid itself must leave the range. The + 1 and - 1 are what guarantee the range shrinks on every step.
The second question is when to stop. We loop while lo <= hi, meaning the range still holds at least one number. Why not lo < hi? When lo equals hi there is still one number to check, and with lo < hi we would stop without checking it. The small picture below follows a search for 7, which is missing, to show how the loop ends.
Dim cells have been ruled out. The search ends when lo passes hi and no number is left in the range.
- target
- 7
- range
- 0 to 9
1The range is the whole array. mid = 4 and a[4] = 16 is bigger than 7, so 7 can only be to the left and hi moves to 3.
- target
- 7
- range
- 0 to 3
2The range is 0 to 3. mid = 1 and a[1] = 5 is smaller than 7, so 7 can only be to the right and lo moves to 2.
- target
- 7
- range
- 2 to 3
3The range is 2 to 3. mid = 2 and a[2] = 8 is bigger than 7, so hi moves to 1.
- target
- 7
- range
- empty
- answer
- -1
4Now lo = 2 and hi = 1, so lo has passed hi and the range is empty. The loop stops and we return -1 after only three comparisons.
Why is the method correct? Before every step, one statement is true, that if the target is anywhere in the array, it is between lo and hi. It is true at the start, because the range is the whole array. Each step only throws away numbers we have proved are too small or too big, so it stays true. If the range becomes empty, as it did for 7, the target cannot be anywhere, and -1 is the honest answer.
One last detail concerns how we compute mid. The obvious formula (lo + hi) / 2 adds lo and hi first, and for an array with more than about a billion numbers that sum can be bigger than the largest int, which wraps around to a negative number. Writing lo + (hi - lo) / 2 gives the same middle without ever forming the large sum, and costs nothing.
5Watching the range shrink while we search for 23
The picture now plays the search for 23 exactly as the Java program runs it. Under the cells you will see lo, mid and hi. Cells outside the range are dimmed, and the cell being compared is highlighted.
lo and hi mark the ends of the range still in play, mid is the cell being compared, and dim cells have been ruled out.
- target
- 23
- range
- 0 to 9
- comparisons
- 0
1We start with the whole array in range, lo = 0 and hi = 9, because 23 could be anywhere.
- target
- 23
- range
- 0 to 9
- comparisons
- 1
2mid = 0 + (9 - 0) / 2 = 4. We compare a[4] = 16 with 23, and 16 is smaller.
- target
- 23
- range
- 5 to 9
- comparisons
- 1
3Since 16 is too small, so is everything to its left. lo moves to mid + 1 = 5, and indexes 0 to 4 are ruled out.
- target
- 23
- range
- 5 to 9
- comparisons
- 2
4mid = 5 + (9 - 5) / 2 = 7. We compare a[7] = 56 with 23, and 56 is bigger.
- target
- 23
- range
- 5 to 6
- comparisons
- 2
5Since 56 is too big, so is everything to its right. hi moves to mid - 1 = 6, leaving only indexes 5 and 6.
- target
- 23
- range
- 5 to 6
- comparisons
- 3
6mid = 5 + (6 - 5) / 2 = 5, because integer division drops the half. We compare a[5] = 23 with 23.
- target
- 23
- answer
- 5
- comparisons
- 3
7They are equal, so we return mid, which is 5. Three comparisons did the work the linear scan needed six for.
Let us read the important frames back. After the first comparison, in the third frame, half the array has gone dim, five numbers ruled out by one look at 16. After the second, the range is down to two numbers. In the sixth frame notice how mid is computed when the range has an even number of cells. (6 - 5) / 2 is 0 in integer arithmetic, because Java drops the fraction, so mid is the left of the two middle cells. That is fine, since either middle cell splits the range.
Go back to the dictionary for a moment. Each frame is one opening of the book. The range from lo to hi is the part of the book you are still holding open, and moving lo or hi is letting the other part fall closed. Ten numbers took three openings.
6The complete Java program
Here is the complete program. search returns the index of the target or -1. main runs the example, the first and last numbers, a missing number, and an empty array, with what each line prints as a comment.
Let us read search in the order it runs. The first line sets lo to 0 and hi to a.length - 1, so the range starts as the whole array. For an empty array hi is -1, which already makes the range empty. The while loop runs as long as lo <= hi, that is, as long as at least one number is still in play.
Inside the loop we compute mid with lo + (hi - lo) / 2, the overflow-safe middle. Then come the three choices. If a[mid] equals the target we return mid at once. If a[mid] is smaller, the target must be to the right, so lo = mid + 1 throws away mid and everything left of it. Otherwise a[mid] is bigger, and hi = mid - 1 throws away mid and everything to its right. Every pass through the loop either returns or makes the range smaller by at least one, so the loop cannot run forever.
If the loop ends without returning, lo has passed hi, the range is empty, and we return -1. In main, 91 is found at 9 on the fourth comparison, the most this array ever needs, and 7 and the empty array both return -1.
The mistake beginners make most often here is mixing up the two ways of writing the range. Our hi is the last index still in play, so the loop test is lo <= hi and the update is hi = mid - 1. Some programs instead let hi mean one past the end, with hi = a.length, lo < hi and hi = mid. Both work, but mixing lines from the two styles skips a number or loops forever.
7How much it costs, and the cases at the edges
Let us count on the example first. Ten numbers needed three comparisons to find 23 and at most four for any target, because each comparison at least halves the range, and 10 becomes 5, then 2, then 1, then nothing. The number of times you can halve n before reaching one is called the base-two logarithm of n, written log n. So the time is O(log n). For a million numbers that is about 20 comparisons, and for a billion about 30, where the linear scan could need a billion. The extra space is three int variables, whatever the size of the array, so O(1).
| Approach | Time | Extra space | Needs sorted input? |
|---|---|---|---|
| Linear scan from the left | O(n) | O(1) | no |
| Build a hash set, then look up | O(n) to build, then O(1) | O(n) | no, and it gives no index |
| Binary search | O(log n) | O(1) | yes |
Now the edge cases. An empty array starts with lo = 0 and hi = -1, so the loop never runs and we return -1. A one-number array starts with lo = hi = 0, which is exactly the case lo <= hi exists for, and the single comparison decides the answer. A target smaller than every number keeps moving hi left until it passes lo, and one larger than every number keeps moving lo right, and both return -1.
One case the code cannot protect against is an array that is not sorted. Binary search on 5, 2, 9 looking for 2 compares 2 with the middle value 2 and is lucky, but looking for 5 it compares with 2, decides 5 must be to the right, and returns -1 although 5 is at index 0. The method trusts the order completely, which is why the first clarifying question matters.
8Follow-up questions
How would you find the first position of a target that appears several times?
We change what happens when a[mid] equals the target. Instead of returning at once, we remember mid as the best answer so far and set hi = mid - 1, so the search carries on to the left in case an earlier copy exists. When the range empties, the remembered index is the first copy, or -1 if we never saw one. Each step still halves the range, so it stays O(log n). For the last copy we do the mirror image and move lo = mid + 1 instead.
Can you write it recursively?
Yes. The method takes lo and hi as parameters. If lo is greater than hi it returns -1. Otherwise it computes mid, returns mid on a match, and otherwise calls itself on lo to mid - 1 or on mid + 1 to hi. It does the same comparisons, but each call waits on the call stack, so it uses O(log n) space instead of O(1). That is small, about 30 calls for a billion numbers, but the loop is simpler and is what most interviewers expect.
What does Java's own Arrays.binarySearch return for a missing value?
It returns a negative number that also tells you where the value would go. If the value would belong at index p to keep the array sorted, it returns minus p minus one. For 7 in our array, 7 would belong at index 2, before 8, so it returns -3. The minus one is there so that a value that belongs at index 0 returns -1 rather than 0, which would look like a match.
9Conclusion
We searched a sorted array by keeping a range from lo to hi, comparing the target with the middle element, and moving lo to mid + 1 or hi to mid - 1 so that the half which cannot hold the target is thrown away. The loop runs while lo <= hi and returns -1 when the range is empty. It costs O(log n) time and O(1) space. The clue to remember is the word sorted: when one comparison can rule out a whole side, look in the middle and halve.
Open with
Let me confirm the setup. The array is sorted in increasing order, I return the index of the target or -1 if it is missing, and any index is fine if there are duplicates.
Then, if they want more
A linear scan works but is O(n), and it ignores the fact that the array is sorted. Because it is sorted, comparing the target with the middle element tells me which half can contain it, so I will use binary search.
I keep lo and hi as the inclusive ends of the range that could still hold the target, starting at 0 and length minus one. While lo is at most hi, I compute mid as lo plus (hi minus lo) over two, which avoids integer overflow. If a[mid] equals the target I return mid.
If it is smaller I set lo to mid plus one, and if it is bigger I set hi to mid minus one. The plus and minus one guarantee the range shrinks, so the loop terminates. If the range becomes empty, I return -1.
Each step halves the range, so it is O(log n) time, and it uses O(1) extra space. An empty array returns -1 immediately.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 16 times in that collection. How it is counted
- Official documentation
- java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Search for a number in a sorted array using binary search.": https://scrivio-interview-library.netlify.app/data-structures/solutions/search-for-a-number-in-a-sorted-array-using-binary-search-d89e53/
Coding patterns, question 5 of 15 Back to the path
More binary search questions