Algorithms
Searching and sorting, the abstract data types and how to build them, and Big O for comparing algorithms.
Linear search and binary search
Linear search checks every item in turn; binary search halves a sorted list each time, so it needs far fewer checks.
| Linear search | Binary search | |
|---|---|---|
| How it works | checks each item in turn, from the start | compares the middle item with the target, discards the half that cannot hold the target, and repeats on the half that is left |
| Stops when | it finds the target or reaches the end | it finds the item or nothing is left |
| Works on | any list | a sorted list only |
| Most comparisons | n items may need n | 15 items: at most 4; 1024 items: at most 11 |
Binary search is like finding a word in a paper dictionary. Open it in the middle, then keep only the half that can hold the word.
Remember:Each comparison discards about half of what is left. So doubling the data adds only one comparison.
FUNCTION BinarySearch(Target : INTEGER) RETURNS INTEGER DECLARE Low : INTEGER DECLARE High : INTEGER DECLARE Mid : INTEGER Low ← 1 High ← 15 WHILE Low <= High Mid ← (Low + High) DIV 2 IF List[Mid] = Target THEN RETURN Mid ENDIF IF List[Mid] < Target THEN Low ← Mid + 1 ELSE High ← Mid - 1 ENDIF ENDWHILE RETURN -1 // not found ENDFUNCTION
Bubble sort and insertion sort
Bubble sort swaps neighbours until a pass makes no swaps; insertion sort slides each item back into its place.
Bubble sort:
- Go through the list, comparing each pair of neighbours.
- Swap them if they are in the wrong order.
- After each pass, the largest remaining item is in its final place.
- If a pass makes no swaps, every pair is in order. The list is sorted, so the sort stops.
Insertion sort takes each item in turn. It slides the item back into its place among the sorted items before it. It is like sorting playing cards in your hand.
How long either sort takes depends on two things: the number of items and their starting order.
| Starting order | Bubble sort | Insertion sort |
|---|---|---|
| nearly sorted | quick | quick |
| reversed | the most work | the most work |
DECLARE Swapped : BOOLEAN DECLARE Temp : INTEGER DECLARE Last : INTEGER DECLARE Index : INTEGER Last ← 7 // 8 items, so 7 pairs REPEAT Swapped ← FALSE FOR Index ← 1 TO Last IF List[Index] > List[Index + 1] THEN Temp ← List[Index] List[Index] ← List[Index + 1] List[Index + 1] ← Temp Swapped ← TRUE ENDIF NEXT Index Last ← Last - 1 UNTIL Swapped = FALSE OR Last = 0
Abstract data types, and building one from another
An ADT is data plus the operations allowed on it, described by what it does, not how it is stored.
An abstract data type (ADT) is a collection of data together with the operations allowed on it. It is described by what it does, not by how it is stored.
In the exam you build each ADT from a language's built-in types. These are arrays, records, and integer variables used as pointers (they hold the index of another item).
| ADT | Built from |
|---|---|
| Stack | an ARRAY + TopOfStack |
| Queue | an ARRAY + FrontPointer, RearPointer, Length |
| Linked list | an ARRAY of records (Data, Pointer) + StartPointer, FreeListPointer |
| Binary tree | an ARRAY of records (Data, LeftPointer, RightPointer) + RootPointer |
| Dictionary | an ARRAY of records (Key, Value), or a hash table |
One ADT can also be built from another. Examples: a stack from a linked list, or a queue from two stacks.
Watch out:These notes start arrays at 1 and use 0 as the null pointer. An exam may start at 0 and use −1, so say which you use.
The stack
A stack is last in, first out: you push items onto the top and pop them from the top.
A stack is like a pile of plates: you add to the top and take from the top.
In an array, a stack needs one pointer, TopOfStack. It holds the index of the top item. 0 means the stack is empty.
| Push (add an item) | Pop (take an item) | |
|---|---|---|
| First check | Is the stack full? | Is the stack empty? |
| If yes | report overflow | report underflow |
| If no | add 1 to TopOfStack, then store the item there | read the item at TopOfStack, then subtract 1 |
Stacks hold:
- the return addresses of subroutine calls
- undo histories
- the values while Reverse Polish notation is evaluated
CONSTANT MaxSize = 6 DECLARE Stack : ARRAY[1:MaxSize] OF INTEGER DECLARE TopOfStack : INTEGER TopOfStack ← 0 // 0 means empty PROCEDURE Push(Item : INTEGER) IF TopOfStack = MaxSize THEN OUTPUT "Stack full - overflow" ELSE TopOfStack ← TopOfStack + 1 Stack[TopOfStack] ← Item ENDIF ENDPROCEDURE
The queue: linear and circular
A queue is first in, first out: items join at the rear and leave from the front.
A queue is like the line at the school canteen: the first to join is the first served.
In an array, a queue needs FrontPointer, RearPointer and Length (the number of items).
| Linear queue | Circular queue | |
|---|---|---|
| The pointers | only move forwards | both wrap round to the first position |
| Space freed at the front | never used again | reused |
| Enqueue (join) | Dequeue (leave) | |
|---|---|---|
| First check | if Length = MaxSize, it is full | if Length = 0, it is empty |
| Otherwise | move RearPointer on, store the item, add 1 to Length | read the item at FrontPointer, move FrontPointer on, subtract 1 from Length |
CONSTANT MaxSize = 5 DECLARE Queue : ARRAY[1:MaxSize] OF STRING DECLARE FrontPointer : INTEGER DECLARE RearPointer : INTEGER DECLARE Length : INTEGER FrontPointer ← 1 RearPointer ← 0 Length ← 0 PROCEDURE Enqueue(Item : STRING) IF Length = MaxSize THEN OUTPUT "Queue full" ELSE RearPointer ← RearPointer + 1 IF RearPointer > MaxSize THEN RearPointer ← 1 // wrap round ENDIF Queue[RearPointer] ← Item Length ← Length + 1 ENDIF ENDPROCEDURE
The linked list: find, insert, delete
A linked list keeps its items in order by pointers, so insert and delete only change pointers.
A linked list keeps its items in order by pointers, not by position.
- Each node holds its data and a pointer to the next node.
- StartPointer holds the first node.
- A null pointer marks the end.
- The unused nodes are chained into a free list, started by FreeListPointer.
| To... | Do this |
|---|---|
| Find an item | start at StartPointer and follow the pointers |
| Insert | take the first node from the free list, store the data in it, and change two pointers to put it in place |
| Delete | change the previous node's pointer to skip the node, then give the node back to the free list |
Remember:Nothing is moved. Only pointers change.
FUNCTION FindItem(Wanted : STRING) RETURNS INTEGER DECLARE Current : INTEGER DECLARE Found : BOOLEAN Current ← StartPointer Found ← FALSE // the Found flag: List[NullPointer] is never read WHILE Current <> NullPointer AND Found = FALSE IF List[Current].Data = Wanted THEN Found ← TRUE ELSE Current ← List[Current].Pointer ENDIF ENDWHILE RETURN Current // NullPointer if not found ENDFUNCTION
The binary search tree: insert and find
In a binary search tree, smaller items always go to the left of a node and larger items to the right.
In a binary tree, each node has at most two children: a left one and a right one. Pointers reach them.
In a binary search tree:
- every item in a node's left subtree is smaller than it
- every item in its right subtree is larger
To insert a new item:
- Start at the root.
- Go left if the new item is smaller. Go right if it is larger.
- Repeat until you reach a null pointer. Attach the new node there.
To find an item, follow the same path. Reaching a null pointer means it is not there.
Remember:Reading the tree in-order (left subtree, node, right subtree) gives the items in sorted order.
FUNCTION FindNode(Wanted : INTEGER) RETURNS INTEGER DECLARE Current : INTEGER Current ← RootPointer WHILE Current <> NullPointer IF Tree[Current].Data = Wanted THEN RETURN Current ENDIF IF Wanted < Tree[Current].Data THEN Current ← Tree[Current].LeftPointer ELSE Current ← Tree[Current].RightPointer ENDIF ENDWHILE RETURN NullPointer ENDFUNCTION
Dictionaries and graphs
A dictionary stores key–value pairs with unique keys; a graph stores nodes and the edges between them.
A dictionary is a collection of key–value pairs. Every key is unique. For example, the key is a student ID and the value is the student's name.
You can add a pair, and look up or delete a pair by its key.
| A dictionary built from | Speed |
|---|---|
| an array of key–value records, searched in order | slower |
| a hash table: the key is hashed to the index of its slot | much faster |
A graph is an ADT made of nodes and the edges between them. Edges may be weighted and directed. Use a graph when the data is about connections:
- roads between towns
- links between web pages
Exam:You will not be asked to write code for a graph.
Big O: how the work grows
Big O notation shows how an algorithm's time or memory grows as the number of items, n, grows.
Big O notation describes how one of these grows as n grows:
- time complexity: the time an algorithm takes
- space complexity: the memory it needs
It describes the worst case and ignores constant factors.
| Big O | How it grows | Example |
|---|---|---|
| O(1) | stays the same, whatever n is | reading an array element by its index |
| O(log n) | slowly | binary search |
| O(n) | in step with n | linear search |
| O(n²) | with the square of n | bubble sort and insertion sort in the worst case, because there is a loop inside a loop |
| O(2ⁿ) | doubles with every extra item | — |
For space, both sorts need O(1) extra memory. But recursion (Chapter 24) n calls deep needs O(n).
worst case Big O n = 10 n = 1 000 n = 1 000 000
binary search O(log n) 4 10 20
linear search O(n) 10 1 000 1 000 000
bubble sort O(n²) 45 499 500 499 999 500 000
Bubble sort's count is about n² ÷ 2:
Big O ignores the ÷ 2.
On a list already in order, bubble
sort (with its no-swap stop) and
insertion sort make n - 1 comparisons:
O(n). O(n²) is their worst case.RUN THE PSEUDOCODE
Write the pseudocode your syllabus uses and press Run. Assignment is the arrow — type <- and it works the same as ←. Both syllabuses are accepted, so OUTPUT and PRINT both work; where a word differs from the one the exam prints, the runner says so.
Press Run to see what it doesTotal ← 0
FOR Count ← 1 TO N
Total ← Total + Count
NEXT Count
OUTPUT TotalSTARTN = 5
| Count | Total | OUTPUT |
|---|---|---|
One row per pass through the loop. Leave a cell blank if it does not change on that pass.
KEY TERMS
CHECK YOURSELF
1.A name in the middle of a linked list held in an array is deleted. What changes?
2.Which traversal of a binary search tree gives the values in sorted order?
3.A stack is:
4.What is the Big O complexity of a binary search?
5.What must be true before a binary search will work?
6.What does the time a bubble sort or an insertion sort takes depend on?
7.In a circular queue in an array, what happens when RearPointer passes the last position?