Algorithms

Computer Science A2 · Computational thinking and Problem-solving. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science A2 topics

The idea

A linear search checks each item in turn, so it works on any list. A binary search needs the items in order: it looks at the middle item and throws away the half that cannot hold the target, again and again.

Bubble sort compares neighbours and swaps them if they are in the wrong order. Insertion sort takes each item and moves it back into its correct place in the sorted part. Both are fast on data that is nearly sorted and slow on large, mixed-up data.

An Abstract Data Type (ADT) is a set of data with the operations allowed on it: stack, queue, linked list, binary tree, dictionary and graph. Algorithms are compared with Big O notation for time and memory.

Rules to remember

Common mistake

Students use a binary search on unsorted data, or write Low ← Mid and High ← Mid. The middle item has already been checked, so use Mid + 1 and Mid − 1, or the search may never end.

Worked example

A binary search looks for 36 in the sorted array [4, 9, 13, 18, 22, 27, 31, 36, 40, 45, 51], indexed from 1 to 11. How many items are compared with 36?

  1. Low = 1, High = 11, Mid = 12 DIV 2 = 6. Item 6 is 27, too small, so Low = 7.
  2. Mid = (7 + 11) DIV 2 = 9. Item 9 is 40, too large, so High = 8.
  3. Mid = (7 + 8) DIV 2 = 7. Item 7 is 31, too small, so Low = 8.
  4. Mid = (8 + 8) DIV 2 = 8. Item 8 is 36: found.

Answer: 4 comparisons (items 27, 40, 31, 36). A linear search would need 8.

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Artificial Intelligence (AI)Recursion →Take a Computer Science A2 test