Computer Science Essentials, Unit 1, Lesson 2 of 7

Linear search and binary search

About 3 min to read, then 7 practice questions

Which search, and why

Each comparison in a binary search halves what is left, so even huge lists need very few comparisons.

Items in a sorted listLinear search, worst caseBinary search, worst case
884
1001007
1 0001 00010
1 000 0001 000 00020

To work out the most comparisons a binary search could need, halve the number of items again and again, dropping any remainder, until you reach 1. Count the numbers in the chain, including the first number and the 1.

For 40 items: 40, 20, 10, 5, 2, 1. That is 6 numbers, so at most 6 comparisons. A linear search of the same list could need 40, one for every item.

  • Use binary search on a long list that is sorted (or that you will search many times, so sorting it once is worth it).
  • Use linear search when the list is not sorted, or is short, or changes all the time. It is also simpler to write.

Practise this

7 questions, about 6 min

  • XP for each right first time
  • Fills in your course map

Sign in to keep your progress.

Start practising