Data Structures
Data Structures
Page 1 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Arrays
Your notes
1D Arrays
What is an Array?
An array is an ordered, static set of elements
Can only store 1 data type
A 1D array is a linear array
Structure of a 1D array
Example in Pseudocode
In this example we will be creating a one-dimensional array called ‘array’ which contains 5 integers.
To create the array we can use the following syntax:
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5
We can access the individual elements of the array by using the following syntax:
array[index]
Page 2 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
We can also modify the individual elements by assigning new values to specific indices using the
following syntax:
array[index] = newValue Your notes
We can also use the len function to determine the length of the array by using the following syntax:
len(array)
In the example we have iterated through the array to output each element within the array. We have
used a For Loop for this.
// Creating a one-dimensional array
array array[5]
array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5
// Length of array
length = len(array)
print(length)
Example in Python
Creating a one-dimensional array called ‘array’ which contains 5 integers.
Create the array with the following syntax:
array = [1, 2, 3, 4, 5]
Page 3 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Access the individual elements of the array by using the following syntax:
array[index]
Your notes
Modify the individual elements by assigning new values to specific indices using the following syntax:
array[index] = newValue
Use the len function to determine the length of the array by using the following syntax:
len(array)
In the example the array has been iterated through to output each element within the array. A for loop
has been used for this
# Creating a one-dimensional array
array = [1, 2, 3, 4, 5]
# Output:
#1
# 10
#3
#4
#5
Example in Java
Creating a one-dimensional array called ‘array’ which contains 5 integers.
To create the array, use the following syntax:
int[] array = {1, 2, 3, 4, 5};
Page 4 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Access the individual elements of the array by using the following syntax:
array[index]
Your notes
Modify the individual elements by assigning new values to specific indices using the following syntax:
array[index] = newValue;
Use the length function to determine the length of the array by using the following syntax:
array.length;
In the example, the array has been iterated through to output each element within the array. A for loop
has been used for this
// Output:
// 1
// 10
// 3
// 4
// 5
Page 5 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
2D Arrays
A 2D array can be visualised as a table Your notes
When navigating through a 2D array you first have to go down the rows and then across the columns to
find a position within the array
Structure of a 2D array
Example in Pseudocode
// Define the dimensions of the 2D array
ROWS = 3
COLS = 4
Example in Python
Page 6 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Example in Java
// Method 1: Initialising an empty 2D array
int rows = 3;
int cols = 4;
int[][] array2D = new int[rows][cols];
// The above code creates a 2D array with 3 rows and 4 columns, filled with zeros.
3D Arrays
A 3D array can be visualised as a multi-page spreadsheet and can also be thought of as multiple 2D
arrays
Selecting an element within a 3D array requires the following syntax to be used:
3DArrayName[z, y, x]
This is where z is the array index, y is the row index and x is the column index
Page 7 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Structure of a 3D array
Example in Pseudocode
// Define the dimensions of the 3D array
ROWS = 3
COLS = 4
DEPTH = 2
Example in Python
# Method 1: Initialising an empty 3D array
rows = 3
cols = 4
depth = 2
Page 8 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Example in Java
// Method 1: Initialising an empty 3D array
int rows = 3;
int cols = 4;
int depth = 2;
int[][][] array3D = new int[rows][cols][depth];
// The above code creates a 3D array with 3 rows, 4 columns, and 2 depths, filled with zeros.
Page 9 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
ID firstName surname
The above example contains 3 records, where each record has 3 fields. A record can be declared as
follows
Example in Pseudocode
personDataType = record
integer ID
string firstName
string surname
endRecord
Example in Python
class Person:
def __init__(self, ID, firstName, surname):
self.ID = ID
self.firstName = firstName
self.surname = surname
Page 10 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
In the code above, a class is defined called “Person” with an ‘__init__’ method that initialises the fields
of the record
Create an instance of the “Person” record called ‘person_record’ with an ID of 1, first name “Tony”, and
surname “Smith”
Finally access and print the values of the fields using dot notation (‘object.field’)
Example in Java
public class Person {
private int ID;
private String firstName;
private String surname;
Page 11 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Define a class called ‘Person’ with private fields for ID, firstName, and surname
Then a constructor that allows you to set these fields when creating an instance of the record
Additionally, provide getter and setter methods for each field to access and modify their values
To use the record in Java, create an instance of ‘Person’ class and set or retrieve the field values using
the provided methods
For example:
public class Main {
public static void main(String[] args) {
Person personRecord = new Person(1, "Tony", "Smith");
This creates an instance of the ‘Person’ record called ‘personRecord’ with an ID of 1, first name “Tony”,
and surname “Smith”
Then uses the getter methods to retrieve the field values and print them to the console
Lists
What is a List?
A list is a data structure that consists of a number of items where the items can occur more than once
Lists are similar to 1D arrays and elements can be accessed in the same way. The difference is that list
values are stored non-contiguously
Page 12 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
This means they do not have to be stored next to each other in memory, which is different to how data is
stored for arrays
Your notes
Lists can also contain elements of more than one data type, unlike arrays
Example in Pseudocode
list pets = ["dog", "cat", "rabbit", "fish"]
Example in Python
pets = ["dog", "cat", "rabbit", "fish"]
Example in Java
import java.util.ArrayList;
import java.util.List;
WORKED EXAMPLE
A programmer has written the following code designed to take in ten names then print them in a
numbered list.
name1 = input("Enter a name: ")
name2 = input("Enter a name: ")
name3 = input("Enter a name: ")
name4 = input("Enter a name: ")
Page 13 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
It has been suggested that this code could be made more efficient and easier to maintain using an
array or a list.
Write a more efficient version of the programmer’s code using an array or a list.
5 marks
How to answer this question:
Start by having a variable names which is initialised as an empty list []
names = []
Then have a for loop run from i = 0 to i = 9 (inclusive), indicating that it will iterate 10 times
for i = 0 to 9
Inside the loop, the input() function is used to prompt the user to enter a name. The entered
name is then appended to the names list using the append() method
names.append(input(“Enter a name: “))
After the first for loop finishes executing, the list names will contain 10 names entered by the
user
Then a second for loop also runs from i = 0 to i = 9 (inclusive)
for i = 0 to 9
Inside this loop, the print() function is used to display the index of each name (incremented by 1)
along with the name itself. The expression i + 1 represents the current index, and (i + 1) + ". " is
concatenated with names[i] to form the output string
print((i+1)+”. “+names[i])
The loop repeats this process for each name in the names list, printing the index number and
corresponding name on separate lines
Page 14 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Answer:
Example answer that gets full marks: Your notes
names = []
for i = 0 to 9
names.append(input(“Enter a name: “))
next i
for i = 0 to 9
print((i+1)+”. “+names[i])
next i
Manipulating Lists
There are a range of operations that can be performed involving lists in the table below:
remove(value) Removes the value the first time it appears in the list Pets.remove(cat)
Tuples
Page 15 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
What is an Tuple?
A tuple is an ordered set of values of any type Your notes
It is immutable, this means that it can’t be changed
Elements, therefore, can’t be added or removed once it has been created
Tuples are initialised using regular brackets instead of square brackets
Elements in a tuple are accessed in a similar way to elements in an array, with the exception that values
can’t be changed
Example in Pseudocode
tuple1 = (1, 2, 3)
Example in Python
person = ("John", 25, "USA")
print(person)
Array A fixed-size collection of elements and need random access to List of student
elements inside by index. They are efficient for accessing grades
elements by index but less efficient for dynamic resizing of
insertion/removal of elements in the middle. A table of numbers
for a mathematical
function
A grid of pixels for an
image
Records A group of related data which is a single entity. They are useful for A shopping list
organising and manipulating data with different attributes of
fields. A to-do list
Page 16 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
A list of contacts in an
address book
Your notes
Lists A dynamic collection of elements that may change in size. They A customer record in
provide flexibility for adding, removing and modifying elements. a database
A student record in a
school system
A product record in
an online store
Page 17 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Linked Lists
Your notes
Linked Lists
What is a Linked List?
A linked list is a dynamic data structure that is used to hold an ordered sequence
The items which form the sequence do not have to be in contiguous data locations
Each item is called a node and contains a data field alongside another address which is called a pointer
For example:
0 'Apple' 2
1 'Pineapple' 0
2 'Melon' -
Start = 1 NextFree = 3
The data field contains the value of the actual data which is part of the list
The pointer field contains the address of the next item in the list
Linked lists also store the index of the first item as a pointer
They also store a pointer identifying the index of the next available space
EXAM TIP
Linked lists can only be traversed by following each item’s next pointer until the end of the list is
located
Page 18 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Adding a node
An advantage of using linked lists is that values can easily be added or removed by editing the points
The following example will add the word ‘Orange’ after the word ‘Pineapple’
1. Check there is free memory to insert data into the node
2. Add the new value to the end of the linked list and update the ‘NextFree’ pointer
3 'Orange'
Start = 1 NextFree = 4
3. The pointer field of the word ‘Pineapple’ is updated to point to ‘Orange’, at position 3
1 'Pineapple' 3
4. The pointer field of the word ‘Orange’ is updated to point to ‘Apple’ at position 0
3 'Orange' 0
4. When traversed this linked list will now output: ‘Pineapple’, ‘Orange’, ‘Apple’, ‘Melon’
Removing a node
Page 19 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Removing a node also involves updating nodes, this time to bypass the deleted node
The following example will remove the word ‘Apple’ from the original linked list Your notes
1. Update the pointer field of ‘Pineapple’ to point to ‘Melon’ at index 2
0 'Apple' 2
1 'Pineapple' 2
2 'Melon' -
2. When traversed this linked list will now output: ‘Pineapple’, ‘Melon’
The node is not truly removed from the list; it is only ignored
Although this is easier it does waste memory
Storing pointers themselves also means that more memory is required compared to an array
Items in a linked list are also stored in a sequence, they can only be traversed within that order so an
item cannot be directly accessed as is possible in an array
WORKED EXAMPLE
A coach company offers tours of the UK
A linked list stores the names of cities on a coach tour in the order they are visited.
linked-lists-question
The tour is amended. The new itinerary is London, Oxford, Manchester then York. Explain how
Birmingham is removed from the linked list and how York is added. You may use the diagram to
illustrate your answer.
Page 20 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
4 marks
Answer: Your notes
Example answer that gets full marks:
The first thing you need to do is change the Oxford pointer to go around Birmingham to point to
Manchester. [1]
linked lists WE 1
Then you create a node called York and this is placed at the next free space in the list. [1]
linked lists WE 2
Manchester is kept in the same position and it’s pointer changed to point to York. [1]
Page 21 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
linked lists WE 3
The York node then points to Null. [1] Your notes
linked lists WE 4
Page 22 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Stacks
Your notes
Stacks
What is a Stack?
A stack is a last in first out (LIFO) data structure
Items can only be added to or removed from the top of the stack
Stacks are key structures in the computing world as they are used to reserve an action, such as go back
a page or undo
A real-life example of a stack would be a pile (or stack) of plates at a buffet; you can only take a plate
from the top, and if you need to reach the bottom one you have to remove all the others first
It is often implemented using an array
Where the maximum size required is known in advance, static stacks are preferred as they are easier to
implement and make more efficient use of memory
A stack has 6 main operations, which can be seen below
Operation Description
isEmpty() This checks is the stack is empty by checking the value of the top pointer
push(value) This adds a new value to the end of the list, it will need to check the stack is not full before
pushing to the stack.
peek() This returns the top value of the stack. First check the stack is not empty by looking at the
value of the top pointer.
pop() This removes and returns the top value of the stack. This first checks if the stack is not
empty by looking at the value of the top pointer.
Page 23 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
isFull() Checks if the stack is full and returns the boolean value, this compares the stack size to the
top pointer.
Your notes
Stacks use a pointer which points to the top of the stack, where the next piece of data will be added
(pushed) or the current piece of data can be removed (popped)
Visual Example
This would push Bunny onto the empty stack
Page 24 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 25 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Visual Example
This would pop Ant From the top of the stack. The new top of the stack would become Dog
Note that the data that is ‘popped’ isn’t necessarily erased; the pointer 'top' moves to show that Ant is
no longer in the stack and depending on the implementation, Ant can be deleted or replaced with a null
value, or left to be overwritten
Page 26 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
WORKED EXAMPLE
Your notes
Stacks and queues are both data structures.
A stack is shown below before a set of operations are carried out on it.
Draw what the stack shown below would look like after the following operations:
pop(), push(“A”), push(“B”), pop(), push(“E”), push(“F”)
Pointer Data
→ Z
2 marks
Answer:
Start by using the operation pop() to remove Z from the top of the stack
Pointer Data
→ Y
→ A
Then use the operation push(“B”) to add B to the top of the stack
Pointer Data
→ B
Page 27 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
X Your notes
→ A
→ E
→ F
Page 28 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Y Your notes
Page 29 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Queues
Your notes
Queues
What is a Queue?
A queue is a First in First out (FIFO) data structure
Items are added to the end of the queue and removed from the front
Imagine a queue in a shop where customers are served from the front and new customers join the
back
A queue has a back (tail) pointer and a front (head) pointer.
Much the same as with a stack, an attempt to enqueue an item when the queue is full is called a queue
overflow. Similarly, trying to dequeue an item from an empty queue is called a queue underflow.
A queue can be static or dynamic
There are three types of queues
1. Linear Queue
2. Circular Queue
3. Priority Queue
Main Operations
Operation Description
peek() Return the value of the item from the front of the queue without removing it from the
queue
Page 30 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
isFull() Check whether the queue is full (if the size has a constraint)
Your notes
Queue Keywords
Keyword Definition
Queue An abstract data structure that holds an ordered, linear sequence of items. It is a
First in First out structure.
Static Data Has a fixed size and can’t change at run time.
Structure
Dynamic Data Able to adapt and accommodate changes to the data inside it so it doesn’t waste
Structure as much space in memory.
Linear Queues
What Are Linear Queues?
A linear queue is a data structure that consists of an array.
Items are added to the next available space in the queue starting from the front
Items are then removed from the front of the queue
Page 31 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Enqueue Data
Before adding an item to the queue you need to check that the queue is not full
If the end of the array has not been reached, the rear index pointer is incremented and the new item is
added to the queue
In the example below, you can see the queue as the data Adam, Brian and Linda are enqueued.
Page 32 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Dequeue Data
Before removing an item from the queue, you need to make sure that the queue is not empty
If the queue is not empty the item at the front of the queue is returned and the front is incremented by 1
In the example below, you can see the queue as the data Adam is dequeued
Page 33 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Circular Queues
What Are Circular Queues?
A static array that has a fixed capacity which means that as you add items to the queue you will
eventually reach the end of the array
When items are dequeued, space is freed up at the start of the array
It would take time to move items up to the start of the array to free up space at the end, so a Circular
queue (or circular buffer) is implemented
It reuses empty slots at the front of the array that are caused when items are dequeued
As items are enqueued and the rear index pointer reaches the last position of the array, it wraps around
to point to the start of the array as long as it isn’t full
When items are dequeued the front index pointer will wrap around until it passes the rear index points
which would show the queue is empty
Page 34 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Enqueue Data
Before adding an item to the circular queue you need to check that the array is not full
It will be full if the next position to be used is already occupied by the item at the front of the queue
If the queue is not full then the rear index pointer must be adjusted to reference the next free position
so that the new item can be added
In the example below, you can see the circular queue as the data Lauren is enqueued.
Page 35 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 36 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 37 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Dequeue Data
Before removing an item from the queue, you need to make sure that the queue is not empty
If the queue is not empty the item at the front of the queue is returned
If this is the only item that was in the queue the rear and front pointers are reset, otherwise the pointer
moves to reference the next item in the queue
In the example below, you can see the queue as the data Adam is dequeued
Page 38 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 39 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 40 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
EXAM TIP
When asked to display a queue visually, make sure that you also identify the position of the front and
rear pointers.
WORKED EXAMPLE
Page 41 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
The current contents of a queue called 'colours', have been implemented in an array are shown
below:
Your notes
0 1 2 3 4 5 6 7
↑ front ↑ back
Front = 0
End = 4
The queue has the subprograms enqueue and dequeue. The subprogram 'enqueue' is used to add
items to the queue and the subprogram 'dequeue' removes items from the queue.
Use the following diagram to show the queue shown above after the following program statements
have run:
enqueue(“orange”)
dequeue()
enqueue(“maroon”)
dequeue()
dequeue()
4 marks
Answer:
1. The first thing is to enqueue orange.
0 1 2 3 4 5 6 7
↑ front ↑ back
2. Then apply a dequeue() this will remove the first item in the queue.
0 1 2 3 4 5 6 7
↑ front ↑ back
Page 42 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
0 1 2 3 4 5 6 7
↑ front ↑ back
4. Then apply another dequeue to remove the next item from the front.
0 1 2 3 4 5 6 7
↑ front ↑ back
5. Then apply the final dequeue command to remove the next item from the front.
0 1 2 3 4 5 6 7
↑ front ↑ back
Page 43 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Graphs
Your notes
Graphs
What is a Graph?
A graph is a set of vertices/nodes that are connected by edges/pointers. Graphs can be placed into
the following categories:
Directed Graph: The edges can only be traversed in one direction
Undirected Graph: The edges can be traversed in both directions
Weighted Graph: A value is attached to each edge
Computers are able to process graphs by using either an adjacency matrix or an adjacency list.
The examples below will be illustrated using an adjacency matrix, more information on programming using
both matrices and lists is available in section 8.
Page 44 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 45 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
For this graph, the names are abbreviated to the first letter.
The data in an adjacency matrix for an unweighted graph is symmetric Your notes
To determine the presence or absence of an edge, you inspect the row (or column) that represents a
node. Example: If you wanted to see if there is an edge between Frogmore and Hartlepool you can
look at the cross-section of row 3 (for Frogmore) and column 4 (for Hartlepool)
You need a method (e.g Dictionary) to record which row/column is used for a specific node’s edge
data
The data values for the nodes (in this example names of towns) are not stored in the matrix
Page 46 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 47 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Page 48 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 49 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Page 50 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 51 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Above is the adjacency matrix for a directed weighted graph:
For this graph, the names are abbreviated to the first letter.
Keyword Definition
Directed Graph A directed graph is a set of objects that are connected together, where the edges
are directed from one vertex to another.
Undirected An undirected graph is a set of objects that are connected together, where the
Graph edges do not have a direction.
Weighted Graph A weighted graph is a set of objects that are connected together, where a weight
is assigned to each edge.
Adjacency Also known as the connection matrix is a matrix containing rows and columns which is
Matrix used to present a simple labelled graph.
Adjacency List This is a collection of unordered lists used to represent a finite graph.
Vertices/Nodes A vertex (or node) of a graph is one of the objects that are connected.
Edges/Arcs An edge (or arc) is one of the connections between the nodes (or vertices) of the
network.
Dictionary A collection of names, definitions, and attributes about data elements that are being
used or captured in a database, information system, or part of a research project.
Page 52 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
EXAM TIP
Your notes
It is not important what the graph looks like, but which vertices are connected.
Page 53 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Breadth-First Search
A breadth-first search is a graph traversal algorithm which systematically visits all neighbours of a given
vertex before moving on to their neighbours. It then repeats this layer by layer.
This method makes use of a queue data structure to enqueue each node as long as it is not already in a
list of visited nodes.
Page 54 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
1. Take the example above, the root node, Dunkirk, would be set as the current node and then added to
the visited list
Dunkirk
Page 55 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
1. Moving from left to right, we must check if the connected node isn't already in the visited list, if it is not,
it is enqueued to the queue.
Your notes
The first version of the queue would have appeared as
→ → 2 Hartlepool
→ → 1 Moulton
→ → 0 Bolton
→ → -1 Empty
1. That linked vertex is then added to the visited list. Finally, it is removed from the queue as this process
repeats. This means that all nodes, from left to right are enqueued to the queue in turn, before being
added to the visited list, and then dequeued from the queue
2. Output all of the visited vertices
Our final visited list would appear as
→ → 5 Cardiff
Page 56 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
→ → 4 Teesside
Your notes
→ → 3 Frogmore
→ → 2 Hartlepool
→ → 1 Moulton
→ → 0 Bolton
→ → -1 Empty
Depth-First Search
A depth-first search is a graph traversal algorithm which uses an edge-based system.
This method makes use of a stack data structure to push each visited node onto the stack and then
pop them from the stack when there are no nodes left to visit.
EXAM TIP
There is no right method to use when performing a depth-first search, it simply depends on how the
algorithm is implemented. Most mark schemes commonly traverse the left-most path first,
therefore that will be used in this example.
Using the example from above, Dunkirk, would be set as the current node and then added to the visited list
Dunkirk
1. Then check if the connected node isn't already in the visited list, if it is not, it pushed to the stack.
The first version of the stack would appear as
Page 57 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
4
Your notes
3
→ 2 Bolton
→ 1 Moulton
→ 0 Hartlepool
→ -1 Empty
1. Next, any connected node that is not on the visited list is then pushed to the stack.
2. Then pop the stack to remove the item and set it as the current node.
3. Output all of the visited nodes
Our final visited list would appear as
You could visualise how the graph has been traversed below, with the left-most column first, then the
middle, then the right-most column.
Page 58 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 59 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
As a result, it is more important that there are a clear set of instructions to easily traverse the graph to
find the specific node.
Your notes
A Binary Tree is a special type of graph and it does have an algorithm for adding and deleting items.
This is covered in the content titles’ Binary Search Trees’.
Page 60 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
EXAM TIP
Your notes
It is important to note that it is not important what the graph looks like, but which vertices are
connected.
WORKED EXAMPLE
A puzzle has multiple ways of reaching the end solution. The graph below shows a graph that
represents all possible routes to the solution. The starting point of the game is represented by A,
the solution is represented by J. The other points in the graph are possible intermediary stages.
Page 61 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 62 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Trees
Your notes
Trees Data Structures
What is a Tree?
A tree is a connected, undirected form of a graph with nodes and pointers
Trees have a root node which is the top node; we visualise a tree with the roots at the top and the leaves
at the bottom
Nodes are connected to other nodes using pointers/edges/branches, with the lower-level nodes
being the children of the higher-level nodes
The endpoint of a tree is called a leaf
The height of a tree is equal to the number of edges that connect the root node to the leaf node that is
furthest away from it
Page 63 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Page 64 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
The most common way to represent a binary tree is by storing each node with a left and right pointer.
This information is usually implemented using 2D arrays
Your notes
Post-Order Traversal
1. Left Subtree
2. Right Subtree
3. Root Node
Page 65 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Using the outline method, imagine there is a dot on the right-hand side of each node
Nodes are traversed in the order in which you pass them on the right Your notes
Start at the bottom left of the binary tree
Work your way up the left half of the tree
Visit the bottom of the right half of the tree
Making your way back up toward the root node at the top
Page 66 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Output each node, moving from left to right, just as though you were reading a book
Continue through each level of the tree Your notes
Page 67 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
2. Identify the position where the new value should be inserted according to the rules of a binary tree
If the tree is empty, the new value will become the root node Your notes
If the value is less than the current node’s value, move to the left child
If the value is greater than the current node’s value, move to the right child
Repeat this process until you reach a vacant spot where the new value can be inserted
3. Insert the new value into the identified vacant spot, creating a new node at that position
4. After insertion, verify that the binary tree maintains its structure and properties
Page 68 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
2. Search for the node containing the value you want to remove
Page 69 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
4. After removal, adjust the binary tree structure if necessary to maintain its properties and integrity
Tree Keywords
Keyword Definition
Edge Connects two nodes together and is also known as a branch or pointer
Root A single node which does not have any incoming nodes
Page 70 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Subtree A subsection of a tree consisting of a parent and all the children of a parent
Traversing The process of visiting each node in a tree data structure, exactly once
Page 71 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
To insert the value '2' into the binary tree above we need to compare the item to the nodes in the tree
1. Compare 2 to 10; 2 is smaller than 10, so you go down to the left child
2. Compare 2 to 7; 2 is smaller than 7 so you go down to the left child
3. Compare 2 to 1; 2 is higher than 1 so you go down to the right and add as a child node of 1
Page 72 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 73 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
If the node to be deleted has 1 child, then we copy the value of the child in the node and then delete the
node. In the diagram, '2' has been replaced by '4', which was its child node originally
Your notes
EXAM TIP
Page 74 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Remember that Binary Search Trees can have a maximum of 2 children for each parent node, but it is
not a requirement that they have 2.
Your notes
Page 75 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Hash Tables
Your notes
Hash Tables
What is a Hash Table?
A hash table is an associative array which is coupled with a hash function. The function takes in data and
releases an output. The role of the hash function is to map the key to an index in the hash table.
Each piece of data is mapped to a unique value using the hash function
It is sometimes possible for two inputs to result in the same hashed value. This is known as a collision
A good hashing algorithm should have a low probability of collisions occurring but if it does occur, the
item is typically placed in the next available location. This is called collision resolution
Hash tables are normally used for indexing as they provide fast access to data due to keys having a
unique 1-1 relationship with the address at which they are stored.
Hash tables enable very efficient searching. In the best case, data can be retrieved from a hash table in
constant time
C 67
6 54
I 73
A 65
Page 76 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Page 77 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Collisions are a problem when using hash tables because you can’t store two sets of data at the same
location.
Your notes
There are two ways to handle collisions Linear probing or chaining
Linear Probing
When there is a collision the data is placed in the next free position in the hash table
Either it can probe sequentially or use an interval (e.g check every 3rd slot) until an empty bucket is
found
In the diagram the data with the key A5RD has already been inserted into the location 74 of the table.
When you want to insert B7MF the same hash value is produced
So because the space is already occupied by A5RD it checks the next location which is 75, as this is
occupied it checks the next location which is 76 which is empty so the data will be placed in this
location
If there are lots of collisions the has table can end up very messy
Retrieving Data:
When there has been a collision the data will not be in the correct location. The process of retrieving
data from the table where collisions have been dealt with by linear probing is as follows:
Hash the key to generate the index value
Examine the indexed position to see if the key (which is stored together with the data) matches the
key of the data you are looking for
If there is no match then each location that follows is checked (at the appropriate interval) until the
matching record is found
Page 78 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
If you reach an empty bucket without finding a matching key then the data is not in the hash table
This significantly reduces the efficiency of using a hash table for searching.
Your notes
Hash tables should always be designed to have extra capacity
Chaining
Another way of dealing with collisions is to use linked lists. Instead of storing the actual data in the hash
table, you store a pointer to a location where the data is stored. Each data item is stored as a node with
3 attributes:
The key value
The data
A pointer to the next node
The first value to be stored will have a Null pointer as it is the only item in the list
When there is a collision the pointer for the first node location will be updated to point to the new node
This will create a chain of nodes whose keys resolve to the same hash value
Retrieving data
When collisions have been dealt with using chaining the data will always be accessed through a single
location in the hash table. The process for retrieving it is as follows:
Hash the key to generate the index value
Examine the key of the node to see if it matches the key that you are looking for
If it is not the node you are looking for follow the linked list until you find the node
Page 79 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
If you reach the end of the list without finding a matching key (or the head pointer was null), the data
is not in the hash table
In the worse case (where every key hashes to the same value), you could still end up carrying out a linear Your notes
search
It is important that the hash function is designed and tested to minimise the number of possible
collisions
Rehashing
Items will be added and deleted from the hash table. If the table starts to fill up, or a large number of
items are in the wrong place, the performance of the hash table will degrade. Rehashing is used to
address this problem
Rehashing created a new table (larger if needed). The key for each item in the existing table will be
rehashed and the item will be inserted into the new table
If the new table is larger the hashing algorithm will need to be modified as it will need to generate a
larger range of hash values
Rehashing is also an opportunity to review the overall effectiveness of the hash function and to review
how the collisions are handled
To be sure this is possible, position 65 will be checked to see if it is empty. If it is, the new data item is
inserted into this position
If position 65 already contains data the overflow table will be used
This would take place by checking the first position in the overflow table to see if it is empty.
Page 80 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
If it is not empty, it will iterate through the table until an empty position is found.
Your notes
Page 81 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
ENDFUNCTION
Page 82 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Your notes
Page 83 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers
Head to www.savemyexams.com for more awesome resources
Page 84 of 84
© 2015-2024 Save My Exams, Ltd. · Revision Notes, Topic Questions, Past Papers