edubun
English
1 / 19

2 / 7 · Basic

Searching: linear and binary search

To find one name in a sorted list of a million, binary search never needs more than 20 checks.

Jump to the 11 practice questions

You will learn

  • Search a list one value at a time
  • Count the checks each method needs

Before this: What an algorithm is

1Explain

Looking for one value

Searching is the problem of finding where a value is in a collection, or learning that it is not there. Your phone does it when you type a contact's name, a shop does it when it checks whether an item is in stock, and a spell checker does it for every word you type. The input is a list and a target value. The output is the position of the target, or a sign such as -1 meaning "not found".

2Explore

Linear search

The plainest method is to start at the left and check each value in turn until you find the target or run out of list. This is linear search. It works on any list, sorted or not. Its cost depends on luck: if the target is first, one check is enough; if it is last or missing, you check every value. For a list of n values the worst case is n checks.

Look for 23 from the left. Each step checks one bar; the counter shows how many checks so far.

0123456789

Look for 23, from the left.

Checks 0

3Problem

Checks to find 23

In the same list, how many checks does linear search make to find 23?

Hint

23 is at position 5, counting from 0.

Solution

Answer: 6

Linear search checks from the front without skipping any value. 23 is at position 5 counting from 0, so the sixth check finds it.

4Problem

The worst case

At most how many checks does linear search need for a list of 1,000 values?

Hint

The target is last, or not there at all.

Solution

Answer: 1000

In the worst case (target last or missing) it checks every value.

5Explore

Binary search

If the list is sorted, you can do much better. Think of the number guessing game: someone picks a number from 1 to 100 and answers only "higher" or "lower". A sensible player guesses 50 first. Whatever the answer, half the possibilities are gone. The next guess is the middle of what is left, and so on. Binary search does exactly this with a sorted list.

lo and hi mark the part that is still possible; faded bars are already ruled out. mid is checked each step.

0123456789

Look for 23. The whole list is still possible.

Checks 0

6Problem

Checks for 23, binary

In the list [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], how many checks does binary search make to find 23?

Hint

Middle values checked: 16, then 56, then 23.

Solution

Answer: 3

Each check compares the target with the middle value and discards one side. mid = 4 (16 < 23), then mid = 7 (56 > 23), then mid = 5 (23). Three checks.

7Problem

The middle is 40, the target 25

Binary search checks a middle value 40 while looking for 25. What happens next?

Hint

25 is smaller than 40. Which side can it be on?

Solution

Answer: hi moves to just before the middle

40 > 25, so the target can only be to the left of the middle.

8Explore

When the value is missing

Look for 7. After three checks lo passes hi, nothing is left, and the answer is -1.

0123456789

Look for 7. The whole list is still possible.

Checks 0

9Explain

How many checks?

Each check of binary search at least halves the part that is left. Starting from n values, after one check at most about n/2 remain, after two about n/4, and so on until one value is left. The number of halvings needed to get from n down to 1 is the base 2 logarithm of n, written log₂ n. Counting the final check as well, binary search needs at most ⌊log₂ n⌋ + 1 checks, where ⌊ ⌋ means rounding down.

List size nLinear search, worst caseBinary search, worst case
773
1001007
1,0001,00010
1,000,0001,000,00020
1,000,000,0001,000,000,00030

10Problem

1,000 values

At most how many checks does binary search need for a sorted list of 1,000 values?

Hint

2⁹ = 512 and 2¹⁰ = 1,024.

Solution

Answer: 10

Each check halves the range, so 1,000 values need ⌊log₂ 1000⌋ + 1 = 9 + 1 = 10 checks, since 2⁹ = 512 ≤ 1000 < 1024 = 2¹⁰.

11Problem

Twice as long

A list doubles in size. What happens to the worst-case number of binary search checks?

Hint

One more check halves the doubled list back.

Solution

Answer: It grows by about one

One extra check halves the doubled list back to the old size.

12Problem

The guessing game

You may guess a number from 1 to 100 and are told "higher" or "lower". With the best strategy, how many guesses are always enough?

Hint

2⁶ = 64 is less than 100, 2⁷ = 128 is not.

Solution

Answer: 7

⌊log₂ 100⌋ + 1 = 6 + 1 = 7. Six guesses are not always enough because 2⁶ − 1 = 63 < 100.

13Explain

The catch: the list must be sorted

Binary search only works because, in a sorted list, one comparison tells you which side the target must be on. On an unsorted list the middle value tells you nothing about its neighbours, so you are back to linear search. Sorting takes work of its own (the next two units are about that), so the choice depends on use. If you search a list once, a linear search may be cheapest. If you search the same list thousands of times, sorting it once and then using binary search pays off quickly.

14Problem

One search, unsorted list

You will look up a single value in an unsorted list once. Which is cheaper?

Hint

Sorting alone already looks at every value more than once.

Solution

Answer: Linear search

Sorting alone costs more than one linear pass, so it only pays off when you search many times.

15Practice

Write linear search

Write linearSearch so it prints 4 (the position of 23, counting from 0) and then -1.

Expected output
4
-1
Your code
const list = [4, 8, 15, 16, 23, 42];
function linearSearch(list, target) {
  // Return the index of target, or -1.
}
console.log(linearSearch(list, 23));
console.log(linearSearch(list, 99));
Hint

return -1 goes after the loop, once every value has been checked.

A solution
const list = [4, 8, 15, 16, 23, 42];
function linearSearch(list, target) {
  for (let i = 0; i < list.length; i++) {
    if (list[i] === target) return i;
  }
  return -1;
}
console.log(linearSearch(list, 23));
console.log(linearSearch(list, 99));

16Practice

Finish binary search

Fill in the loop of binarySearch and delete the break line. It should print 5 and then -1.

Expected output
5
-1
Your code
const list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];
function binarySearch(list, target) {
  let lo = 0, hi = list.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    // If list[mid] is the target, return mid.
    // If list[mid] < target, move lo; otherwise move hi.
    break; // delete this line when the loop is done
  }
  return -1;
}
console.log(binarySearch(list, 23));
console.log(binarySearch(list, 7));
Hint

If the middle value is smaller than the target, the target is to the right: move lo.

A solution
const list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];
function binarySearch(list, target) {
  let lo = 0, hi = list.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (list[mid] === target) return mid;
    if (list[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}
console.log(binarySearch(list, 23));
console.log(binarySearch(list, 7));

17Problem

lo = mid

Why can lo = mid (instead of mid + 1) make binary search loop forever?

Hint

Try lo = 4 and hi = 5.

Solution

Answer: With two values left, mid can stay the same every round

If lo = 4 and hi = 5, mid = 4 and lo = mid leaves lo at 4, so the range never shrinks.

18Explain

Common mistakes

Mistake
const list = [2, 5, 8, 12, 16];
let lo = 0, hi = list.length;
const target = 99;
while (lo <= hi) {
  const mid = Math.floor((lo + hi) / 2);
  if (list[mid] < target) lo = mid + 1;
  else hi = mid - 1;
  console.log("checked", mid, list[mid]);
}
Output
checked 2 8
checked 4 16
checked 5 undefined
Fixed
const list = [2, 5, 8, 12, 16];
let lo = 0, hi = list.length - 1;
const target = 99;
while (lo <= hi) {
  const mid = Math.floor((lo + hi) / 2);
  if (list[mid] < target) lo = mid + 1;
  else hi = mid - 1;
  console.log("checked", mid, list[mid]);
}
Output
checked 2 8
checked 3 12
checked 4 16

hi starts at the last index, length - 1. Starting at length reads one place past the end, where JavaScript gives undefined.

Mistake
const list = [91, 2, 56, 23, 8];
function binarySearch(list, target) {
  let lo = 0, hi = list.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (list[mid] === target) return mid;
    if (list[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}
console.log(binarySearch(list, 23));
Output
-1
Fixed
const list = [91, 2, 56, 23, 8].sort((x, y) => x - y);
function binarySearch(list, target) {
  let lo = 0, hi = list.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (list[mid] === target) return mid;
    if (list[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}
console.log(binarySearch(list, 23));
Output
2

On an unsorted list binary search can miss a value that is there. Sort first (with a number comparison), then search.

19

Summary

  • Linear search checks one value at a time: up to n checks.
  • Binary search halves the range that is left: up to ⌊log₂ n⌋ + 1 checks.
  • Binary search only works on a sorted list.
  • A million values: 20 checks at most.
  • Update with mid + 1 and mid − 1 so the range always shrinks.

Next unitSorting 1: bubble, selection and insertion sort
Full text · The whole lesson as one text

Looking for one value

Searching is the problem of finding where a value is in a collection, or learning that it is not there. Your phone does it when you type a contact's name, a shop does it when it checks whether an item is in stock, and a spell checker does it for every word you type. The input is a list and a target value. The output is the position of the target, or a sign such as -1 meaning "not found".

Linear search: one at a time

The plainest method is to start at the left and check each value in turn until you find the target or run out of list. This is linear search. It works on any list, sorted or not. Its cost depends on luck: if the target is first, one check is enough; if it is last or missing, you check every value. For a list of n values the worst case is n checks. A list twice as long can take twice as many checks, which is where the name "linear" comes from: the work grows in a straight line with the size.

function linearSearch(list, target) {
  for (let i = 0; i < list.length; i++) {
    if (list[i] === target) return i;  // found it
  }
  return -1;                             // checked everything
}

Binary search: halve what is left

If the list is sorted, you can do much better. Think of the number guessing game: someone picks a number from 1 to 100 and answers only "higher" or "lower". A sensible player guesses 50 first. Whatever the answer, half the possibilities are gone. The next guess is the middle of what is left, and so on. Binary search does exactly this with a sorted list. It keeps two markers, lo and hi, around the part where the target could still be. It checks the middle value. If that is the target, it is done. If the middle value is smaller than the target, everything to its left is smaller too, so lo moves past the middle. If it is larger, hi moves before the middle. When lo passes hi, nothing is left and the target is not in the list.

function binarySearch(list, target) {
  let lo = 0, hi = list.length - 1;
  while (lo <= hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (list[mid] === target) return mid;
    if (list[mid] < target) lo = mid + 1;  // target is to the right
    else hi = mid - 1;                     // target is to the left
  }
  return -1;
}
A sorted list of 31 numbers. Pick a target, then step through binary search and linear search and compare the number of checks.

How many checks?

Each check of binary search at least halves the part that is left. Starting from n values, after one check at most about n/2 remain, after two about n/4, and so on until one value is left. The number of halvings needed to get from n down to 1 is the base 2 logarithm of n, written log₂ n. Counting the final check as well, binary search needs at most ⌊log₂ n⌋ + 1 checks, where ⌊ ⌋ means rounding down. For 100 values that is 7 checks, which is why the guessing game can always be won in 7 guesses. For 1,000 values it is 10, for a million 20, and for a billion 30.

List size nLinear search, worst caseBinary search, worst case
773
1001007
1,0001,00010
1,000,0001,000,00020
1,000,000,0001,000,000,00030

The catch: the list must be sorted

Binary search only works because, in a sorted list, one comparison tells you which side the target must be on. On an unsorted list the middle value tells you nothing about its neighbours, so you are back to linear search. Sorting takes work of its own (the next two units are about that), so the choice depends on use. If you search a list once, a linear search may be cheapest. If you search the same list thousands of times, sorting it once and then using binary search pays off quickly. This trade between preparing data and answering questions about it runs through the whole subject.

A classic slip in binary search is the update step. Writing lo = mid instead of lo = mid + 1 can make the loop run forever when two values are left, because mid never changes. The middle value has already been checked, so it can be left out of the next range.
Key points
  • Linear search checks one value at a time: up to n checks.
  • Binary search halves the range that is left: up to ⌊log₂ n⌋ + 1 checks.
  • Binary search only works on a sorted list.
  • A million values: 20 checks at most.
  • Update with mid + 1 and mid − 1 so the range always shrinks.

Practice questions from Searching: linear and binary search on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 1 Introduction, 3 Sorting, 9 Breadth-First Search, 10 Depth-First Search (ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes) and Fall 2011 lecture 13 BFS notes (ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011)
  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms (MIT Press)
  • with the CLRS-based Khan Academy algorithms unit by Thomas Cormen and Devin Balkcom of Dartmouth (khanacademy.org/computing/computer-science/algorithms: binary search, selection sort analysis, merge sort, quicksort overview and analysis)
  • MacTutor History of Mathematics, Al-Khwarizmi (mathshistory.st-andrews.ac.uk/Biographies/Al-Khwarizmi: word algorithm from the Latin title Algoritmi de numero Indorum)
  • D. E. Joyce, Euclid's Elements Book VII Propositions 1 and 2 (mathcs.clarku.edu/~djoyce/elements/bookVII)
  • Wolfram MathWorld, Merge Sort (mathworld.wolfram.com/MergeSort.html: proposed by John von Neumann in 1945, after Knuth 1998 p. 159)
  • Stanford CS "Tony Hoare: Quicksort" (cs.stanford.edu/people/eroberts/courses/soco/projects/2008-09/tony-hoare/quicksort.html: devised while a student at Moscow State University for Russian-English machine translation with a tape dictionary, programmed in Algol 60 and published 1961; the year 1959 from the Wikipedia Quicksort article and its cited sources)
  • Bodleian Libraries, Ada Lovelace (blogs.bodleian.ox.ac.uk/adalovelace: 1843 paper, Note G Bernoulli numbers)
  • Fourmilab text of Menabrea's Sketch with Lovelace's notes (fourmilab.ch/babbage/sketch.html)
  • Seven Bridges of Konigsberg (Euler 1736) and Tower of Hanoi (Edouard Lucas, 1883) checked against the Wikipedia articles and their cited sources.

Checked: 2026-10-17