Linear and binary search

GCSE Computer Science (OCR) · OCR J277 · Algorithms and programming (Paper 2) › Algorithms › Searching and sorting algorithms

66 exam-style questions plus unlimited generated ones on this topic, at up to four difficulty levels, with full mark schemes. Notes and past-paper booklets are open to everyone. Practice needs a free account.

Or take a quick quiz: 10 questions on this subtopic in GCSE Computer Science (OCR), marked as you tap.

Revision notes

A linear search checks each item in turn; a binary search repeatedly halves a sorted list. You need to know the steps of each, that binary search needs sorted data, and be able to apply each search to a list and recognise it from code. Expect 'describe the steps' and 'compare the two searches' questions.

Key facts

  • Linear search: check each item in turn from the start until found or the end is reached
  • Linear search works on unsorted data
  • Binary search: the data MUST be sorted
  • Middle position = (first + last) DIV 2
  • Target larger than middle: first = mid + 1; smaller: last = mid − 1
  • Not found when first > last (nothing left to search)
  • Binary search halves the list with every comparison
  • 1000 items: binary search needs at most 10 comparisons; linear search up to 1000

Notes

Linear search

diagram
  • Start at the first item and compare it with the item you are looking for (the target).
  • If it is not a match, move on to the next item. Repeat until the target is found or the end of the list is reached.
  • 80not 531not 5122not 553found94position
    Linear search for 5: each item is checked in turn until it is found
  • It works on unsorted or sorted data and is simple to code.
  • It is slow for large lists: in the worst case every item is checked, so a list of 1000 items can need 1000 comparisons.

Binary search

diagram
  • The data must be sorted first.
  • Find the middle item. In code the middle position is usually mid = (first + last) DIV 2, which rounds down.
  • If the middle item is the target, stop: it has been found.
  • If the target is smaller, discard the middle item and everything after it (last = mid - 1). If it is larger, discard the middle item and everything before it (first = mid + 1).
  • Repeat with the half that is left, until the target is found or there is nothing left to search (first is greater than last), which means it is not in the list.
  • Example: find 40 in 4, 9, 15, 22, 31, 40, 58 (positions 0 to 6). Middle is position 3, value 22. 40 is larger, so search positions 4 to 6. Middle is position 5, value 40: found after 2 comparisons.
  • 4091152223314405586firstmidlast22 < 40, so discard 22 and everythingbefore it: first = 3 + 1 = 44091152223314405586firstmidlastmid = (4 + 6) DIV 2 = 5:the value is 40, so it is found
    Binary search for 40: each comparison discards half of what is left

Which is better?

  • Each comparison in a binary search halves the part of the list still to search, so it is much faster on large lists: at most 10 comparisons for 1000 items.
  • A linear search is better when the list is unsorted (sorting first takes time), very small, or when the target is likely to be near the start.

How to answer each type of question

Describe the steps of a search on given data

3 to 4 marksGrade 5
  1. For binary search, write down the positions and find the middle item using the rule given.
  2. Say what it is compared with and which half is discarded.
  3. Repeat with the new middle item until the target is found (or the list is empty).
  4. Name the actual values you compare: that is where the marks are.

Example. The sorted list 2, 5, 8, 11, 16, 20, 27, 30, 35 is stored in positions 0 to 8. Describe how a binary search would find 30. Use (first + last) DIV 2 for the middle position. [4]

Show the model answerHide the model answer
Compare 30 with the middle item, 16 at position 4 (1). 30 is larger, so discard 16 and every item before it (1). Compare 30 with the new middle item, 27 at position 6; 30 is larger, so discard 27 and the items before it (1). Compare 30 with the middle of positions 7 to 8, which is 30 at position 7: found, so stop (1).

Compare linear and binary search

2 to 4 marksGrade 6
  1. Make a point about efficiency: binary search halves the list each time.
  2. Link it to the size of the data in the question.
  3. For an advantage of linear search, mention unsorted data or very small lists.

Example. A phone stores 500 contacts in alphabetical order.
Explain why a binary search is more efficient than a linear search for finding a contact. [2]

Show the model answerHide the model answer
A binary search halves the number of contacts left to search with each comparison (1), so it needs at most 9 comparisons, whereas a linear search could need 500 (1).

List the items checked in a linear search

1 to 2 marksGrade 4
  1. Start at the first item.
  2. List every item in order up to and including the target.
  3. If the target is not there, every item is checked.

Example. A linear search is used to look for 9 in the list 7, 3, 12, 9, 5.
(a) State the items that are compared with 9, in order. [1]
(b) Explain why a binary search could not be used on this list. [1]

Show the model answerHide the model answer
(a) 7, 3, 12, 9
(1)
(b) The list is not sorted
(1).

Complete or identify search code

3 to 4 marksGrade 7
  1. Look for clues: a mid variable and DIV 2 means binary search; checking every item with a loop from 0 means linear search.
  2. For binary search, the target is larger: first moves to mid + 1; smaller: last moves to mid − 1.
  3. A value such as −1 is often returned to mean 'not found'.

Example. The function returns the position of target in the sorted array items, or −1 if it is not there.

function search(items, target)
   first = 0
   last = items.length - 1
   while first <= last
      mid = (first + last) DIV 2
      if items[mid] == target then
         return mid
      elseif items[mid] < target then
         first = ....(1)....
      else
         last = ....(2)....
      endif
   endwhile
   return ....(3)....
endfunction
(a) Complete the gaps (1) to (3). [3]
(b) Name the search algorithm used. [1]

Show the model answerHide the model answer
(a) (1) mid + 1 (1); (2) mid - 1 (1); (3) -1
(1)
(b) Binary search
(1)

Don’t lose marks

  • Forgetting to say that binary search needs the data to be sorted.
  • Saying binary search 'splits the list in half' without saying it compares the middle item and discards the half that cannot contain the target.
  • Keeping the middle item in the half you search next: it has already been checked.
  • Stopping a linear search too early, or listing items after the target has been found.
  • Choosing a different middle item from the rule given in the question.

More tips

Memory tricks

  • Binary search needs a sorted list, just like looking up a word in a dictionary: open it in the middle, then choose a half.
  • Maximum binary search comparisons: keep halving the number of items until you reach 1, counting the halvings, then add 1. For example 1000, 500, 250, 125, 62, 31, 15, 7, 3, 1 is 9 halvings, so at most 10 comparisons.
  • Powers of 2 check: 210 = 1024, so up to 1023 items need at most 10 comparisons.

Exam technique

  • Write the position numbers above the list before you start a binary search.
  • Quote actual values in 'describe' answers: 'compare 30 with 16' earns more than 'compare with the middle'.
  • If a question asks for an advantage of linear search, 'the data does not need to be sorted' is the safest answer.

What each grade needs

What you need to be able to do, from the first marks up to the top grade.

  1. Grade 3
    Describe how a linear search worksCheck each item in turn from the start until the item is found or the end is reached.
  2. Grade 4
    State the condition needed for binary searchThe data must already be sorted, in ascending or alphabetical order.
  3. Grade 5
    Carry out a binary search on a listFind the middle item, compare, discard half the list, and repeat until found or empty.
  4. Grade 6
    Compare linear and binary searchBinary search is much quicker on large sorted lists; linear search works on unsorted lists.
  5. Grade 7
    Complete or identify search algorithm codeRecognise each search from its code and fill in missing lines, such as first = mid + 1.
  6. Grade 8
    Work out the maximum number of comparisonsBinary search halves the list each time, so 1000 items need at most 10 comparisons.

Quick recall

Cover the answers and test yourself. The app has these as flashcards that come back just before you'd forget them.

Name the search algorithm that compares the target with the middle item of a sorted list and then discards half of the list.
Binary search
Write the letters A to D in the correct order for a binary search.
C, D, A, B
An array holds 50 items. State the smallest number of comparisons a linear search could make when the target is in the array.
1
Complete the sentences using words from the word box.
A binary search starts by comparing the target with the ______ item in the list.
After each comparison, the search ______ the number of items that are left to check.
middle; halves
Give one advantage of using a linear search instead of a binary search.
A linear search works on a list that is not sorted.
A user runs the function and it returns −1. State what this tells the user.
The target is not in the array.

Sample questions

Written for this site in the style of OCR exam questions. They are not taken from real past papers.

Question 1Easy4 marks
(a) Which search algorithm can only be used when the data is sorted?
Tick (✓) one box.
[1]
  • Binary search
  • Linear search
  • Both linear search and binary search
  • Neither linear search nor binary search
(b) Describe how a linear search finds an item in a list.
[2]
(c) Give one advantage of a linear search compared with a binary search.
[1]
Show the answer and mark scheme
(a) Answer: Binary search
(b)
  • checks / compares each item in turn, starting with the first item
  • until the item is found / until the end of the list is reached (the item is not in the list)
(c)
  • the data does not need to be sorted
  • it is simpler to code / understand
  • it can be quicker for a very small list / when the item is near the start of the list
Question 2Medium5 marks
A mobile phone stores 2000 contacts in alphabetical order of name.
(a) Explain why a binary search would usually find a contact more quickly than a linear search.
[2]
(b) State the maximum number of names a linear search would check when looking for a contact.
[1]
(c) The phone also keeps a list of the 20 most recent calls, stored in the order in which the calls were made. Explain why a linear search would be used to find a name in this list.
[2]
Show the answer and mark scheme
(a)
  • each comparison in a binary search discards / halves the part of the list left to search
  • so far fewer comparisons are needed (at most 11 for 2000 items, compared with up to 2000 for a linear search)
(b) Answer: 2000
  • 2000
(c)
  • the list is not sorted by name, and a binary search needs sorted data
  • the list is short, so a linear search is fast enough / sorting it first would take extra time
Question 3Hard7 marks
A library catalogue contains 1000 book titles in alphabetical order.
(a) State the maximum number of titles a linear search would need to check.
[1]
(b) Each comparison in a binary search halves the number of titles still to be searched. Calculate the maximum number of comparisons a binary search would need. Show your working.
[2]
(c) The number of titles doubles to 2000. Describe the effect on the maximum number of comparisons needed by each type of search.
[2]
(d) New titles are added to the catalogue every day. Explain one disadvantage of using a binary search for this catalogue.
[2]
Show the answer and mark scheme
(a) Answer: 1000
  • 1000
(b) Answer: 10 (210 = 1024, which is at least 1000)
  • repeated halving shown (1000 → 500 → 250 → …) / uses 210 = 1024 ≥ 1000
  • 10
(c)
  • linear search: doubles (to 2000)
  • binary search: increases by only one (to 11)
(d)
  • the titles must always be kept in alphabetical order / sorted
  • so each new title must be inserted in the correct place / the list must be sorted again, which takes time

More in Searching and sorting algorithms

Stuck? Get 1-to-1 help.

Chhetri Academy tutors GCSE and A level Maths and Science online, with a free 30-minute trial lesson.