4.1 Computational Thinking & Problem Solving
4.1 Computational Thinking & Problem Solving
19 Computational
COMPUTER SCI ENCE thinking and
Compiled By Engr. Shahzadah Ashraf BandaShah problem-solving
STUDENTS NAME:
_____________________________________________
_____________________________________________
Follow On Facebook :
DATE ISSUED: https://www.facebook.com/shahzad
ah.ashraf
_____________________________________________
For More Resources:
bandashah.com
CONTACT NUMBER:
_____________________________________________
Coming Up CSWS21
Computer Science
Workshop 2021
Cambridge International AS & A Level Computer Science 9618 syllabus for 2021, 2022 and 2023. Subject content
19.2 Recursion
Candidates should be able to: Notes and guidance
Show understanding of recursion Essential features of recursion.
How recursion is expressed in a programming
language.
Write and trace recursive algorithms
When the use of recursion is beneficial
Show awareness of what a compiler has to do to Use of stacks and unwinding
translate recursive programming code
www.cambridgeinternational.org/alevel
19.1 Algorithms
An algorithm (pronounced AL-go-rith-um) is a procedure or formula for solving a problem. The word
derives from the name of the mathematician, Mohammed ibn-Musa al-Khwarizmi, who was part of the
royal court in Baghdad and who lived from about 780 to 850.
It is a step by step set of operations to be performed. It is almost as similar to a cooking recipe in real
life. Algorithms exist that perform calculation, data processing, automated reasoning, sorting of
data, and many other things.
In this chapter, we will be focusing on some of the different sorting and searching algorithms that exist
today.
Linear Sort
This is the simplest kind of searching. It is also called the serial sort or the sequential sort. Searching
starts with the first item and then moves to each item in turn until either a match is found or the search
reaches the end of the data set with no match found.
A criteria will allow a possible match to be found within the records / items stored. If no match is found,
then the process will return the appropriate message.
The Algorithm
Advantages
Linear search is fairly easy to code. For example the pseudo-code below shows the algorithm in
action.
procedure serial_search()
For i = 0 to 19
check_for_match(i, list)
if match_found return 'match found'
Next i
return 'no match found'
end
Page 13 of 40
Good performance over small to medium lists. Computers are now very powerful and so checking
potentially every element in the list for a match may not be an issue with lists of moderate length.
The list does not need to be in any order. Other algorithms only work because they assume
that the list is ordered in a certain way. Serial searching makes no assumption at all about the
list so it will work just as well with a randomly arranged list as an ordered list.
Not affected by insertions and deletion. Some algorithms assume the list is ordered in a
certain way. So if an item is inserted or deleted, the computer will need to reorder the list
before that algorithm can be applied. The overhead of doing this may actually mean that
serial searching platforms better than the other methods.
Disadvantages
May be too slow for oversized lists. Computers take a finite amount of time to search each item,
so naturally, the longer the list, the longer it will take to search using the serial method. The
worst case being no match found and every item had to be checked.
This speed disadvantage is why other search methods have been developed.
Binary Search
Sometimes you may be doing a binary search without realizing it. Suppose you want to find Samuel
Jones in the local telephone book. Would you start from page 1 and then go on from there, page by
page? Unlikely.
You don’t do this because you know an important fact about telephone books - the entries are in
alphabetic order. So what you do is make a guess - J is about halfway down the alphabet and so you
open the telephone book around half way. The page you see has names starting with N. So you know J
will be in the first half of the book. Next you open a page about halfway down the first half - the page
has 'H'. So now Jones must be in the upper half of this section.
You are carrying out a 'Binary search' algorithm. Notice that after only two guesses you are getting
much closer to the answer. If you were carrying out a serial search, you would still be at page 2.
The Algorithm
Page 14 of 40
7) If Yes, Set lower limit L to item + 1 (Force the next search to use the upper half)
8) If No, Set upper limit N to item - 1 (Force the next search to use the lower half)
9) Is lower limit = upper limit, if yes end search (no match found)
10) Repeat from step 3 with the new upper and lower bounds.
It depends.
1) If the list is large and changing often, with items constantly being added or deleted, then the
time it takes to constantly re-order the list to allow for a binary search might be longer than
a simple serial search in the first place.
2) If the list is large and static e.g. telephone number database, then a binary search is very
fast compared to linear search. (in math terms it takes 2logR2R(n) for a binary search
over n items)
3) If the list is small then it might be simpler to just use a linear search
4) If the list is random, then linear is the only way
5) If the list is skewed so that the most often searched items are placed at the beginning, then
on average, a linear search might be better.
If you have an array with N data items and you want to apply Linear and Binary search on this data
set. The worst case will be if the item you want to look for is at the end of the array.
In this case a linear search would take N iterations to retrieve this item.
Whereas, a binary search would take 2 log R2R (n) iterations to retrieve this item.
Insertion Sort
In this method we compare each number in turn with the numbers before it in the list. We then insert
the number into its correct position.
20 47 12 53 32 84 85 96 45 18
We start with the second number, 47, and compare it with the numbers preceding it. There is only one
and it is less than 47, so no change in the order is made. We now compare the third number, 12, with
its predecessors. 12 is less than 20 so 12 is inserted before 20 in the list to give the list
12 20 47 53 32 84 85 96 45 18
Page 15 of 40
This is continued until the last number is inserted in its correct position. In Fig. 3.4.j.1 the blue numbers
are the ones before the one we are trying to insert in the correct position. The red number is the one we
are trying to insert.
Algorithm
1) for j = 2 to length[A]
2) do key = A[j]
3) Insert A[j] into the sorted sequence A[1 . . j - 1].
4) i=j-1
5) while i > 0 and A[i] > key
6) do A[i + 1] = A[i]
7) i=i-1
8) A[i + 1] = key
Simple to code
Very good performance with small lists (how small is small depends on the power of the
computer it is running on)
Page 16 of 40
Very good when the list is almost sorted. In this case very few compares need to be done.
The worst case is when the list is in reverse order.
Sort-stable which means it keeps the relative positions of the elements intact
Very memory efficient - it only needs one extra storage location to make room for the
moving items.
Good with sequential data that is being read in one at a time e.g. tape, hard disk or data being
received sequentially.
Bubble Sort
The Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to
be sorted, comparing each pair and swapping them if they are in the wrong order. The pass through the
list is repeated until no swaps are needed, which indicated that the list is sorted. The algorithm gets its
name from the way larger elements “bubble” to the top of the list. It is a very slow was of sorting data
and rarely used in the industry. There are much faster sorting algorithms out there such as the Quick
sort or the Heap sort.
Animation link:
http://en.wikibooks.org/wiki/Alevel_Computing/AQA/Problem_Solving,_Programming,_Data_Repres
entation_and_Practical_Exercise/Problem_Solving/Searching_and_sorting#/media/File:Bubble sort.gif
Step-by-step example
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number
using bubble sort algorithm. In each step, elements written in bold are being compared.
First Pass:
(5 14 2 8 ) → (1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them since 5 > 1
(1 5 42 8 ) → (1 4 5 2 8 ), It then compares the second and third items and swaps them since 5 > 4
(1 4 2 58 ) → (1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not
swap them.
The algorithm has reached the end of the list of numbers and the largest number, 8, has bubbled to
the top. It now starts again.
Page 17 of 40
Second Pass:
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm
needs one whole pass without any swap to know it is sorted.
Third Pass:
(1 2 4 5 8) → (1 2 4 5 8)
(1 2 4 5 8) → (1 2 4 5 8)
(1 2 4 5 8) → (1 2 4 5 8)
(1 2 4 5 8) → (1 2 4 5 8)
Algorithm
The algorithm can be expressed as:
If the data is partially sorted, then the algorithms may take less iterations.
If the data is in descending order and you want to sort the data in ascending order, then the algorithm
will take maximum iterations to sort the data.
Page 18 of 40
Linked List
Insertion
Consider Fig. 1a which shows a linked list and a free list. The linked list is created by removing cells from
the front of the free list and inserting them in the correct position in the linked list.
Now suppose we wish to insert an element between the second and third cells in the linked list. The
pointers have to be changed to those in Fig. 1b.
The algorithm must check for an empty free list as there is then no way of adding new data. It must also
check to see if the new data is to be inserted at the front of the list. If neither of these is needed, the
algorithm must search the list to find the position for the new data.
Page 19 of 40
7) If HEAD is NULL then
a. Pointer in cell pointed to by NEW is set to NULL
b. Set HEAD to NEW and stop.
8) If data is less than data in first cell THEN
a. Set pointer in cell pointed to by NEW to HEAD.
b. Set HEAD to NEW and stop
9) Search list sequentially until the cell found is the one immediately before the new cell that is
to be inserted. Call this cell PREVIOUS.
10) Copy the pointer in PREVIOUS into TEMP.
11) Make the pointer in PREVIOUS equal to NEW
12) Make the pointer in the cell pointed to by NEW equal to TEMP and stop.
Deletion
Suppose we wish to delete the third cell in the linked list shown in Fig. 3.4.h.1. The result is shown in
Fig. 1c.
In this case, the algorithm must make sure that there is something in the list to delete.
Page 20 of 40
Amendment
Amendments can be done by searching the list to find the cell to be amended.
The algorithm is:
Searching
Assuming that the data in a linked list is in ascending order of some key value, the following
algorithm explains how to find where to insert a cell containing new data and keep the list in
ascending order. It assumes that the list is not empty and the data is not to be inserted at the
head of the list.
Note: A number of methods have been shown here to describe algorithms associated with linked lists.
Any method is acceptable provided it explains the method. An algorithm does not have to be in pseudo
code, indeed, the sensible way of explaining these types of algorithm is often by diagram.
Binary Trees
The TREE is a general data structure that describes the relationship between data items or 'nodes'. The
parent node of a binary tree has only two child nodes.
Page 21 of 40
Insertion - binary tree
One of the most powerful uses of the TREE data structure is to sort and manipulate data items. Most
databases use the Tree concept as the basis of storing, searching and sorting its records. The Binary tree
mostly holds data items in a sorted order, but with the addition of a simple rule
Rule: The LEFT node always contain values that come before the root node and the RIGHT node always
contain values that come after the root node.
For numbers, this means the left sub-tree contains numbers less than the root and the right sub-tree
contains numbers greater than the root. For words, as might be in a sorted dictionary, the order is
alphabetic.
A sequence of numbers are to formed into a binary search tree. These numbers are available in this order:
Task: form a sorted binary tree diagram. This is done step by step.
1) The first item is 20 and this is the root node, so begin the diagram
Page 22 of 40
This is a binary search tree, so there are two child nodes available, the LEFT and the RIGHT.
The next number is 17, the rule is applied (left is less than parent node) and so it has to be the
LEFT node, like this.
The next number is 29, this is higher than the root node so it goes to the RIGHT sub-tree which
happens to be empty at this stage, so the tree now looks like
The next number is 22. This is more that the root and so need to be on the RIGHT sub-tree. The
first node is already occupied. So the rule is applied again to that node, 22 comes before 29 and
so it needs to be on the LEFT sub-tree of that node, like this.
Page 23 of 40
5) Sequence 20, 17, 29, 22, 45, 9, 19
The next number is 45, this is more than the root and more than the first right node, so it is
placed on the right side of the tree like this.
The next number is 9 which is less than the root, the first left node is occupied and 9 is less than
that node too, so it is placed on the left sub-tree, like this
The next number is 19, which is less than the root, so it will need to be in the left sub-tree.
It is greater than the occupied 17 node and so it is placed in the right sub-tree, like this.
Page 24 of 40
Deletion
Data in a tree serves two purposes (one is to be the data itself) the other is to act as a reference for the
creation of the subtree below it. If Joh is deleted there is no way of knowing which direction to take at
that node to find the details of the data beneath it.
Solution 1 is to store Joh’s subtree in temporary storage and then rewrite it to the tree after Joh is
deleted. (The effect is that one member of the subtree will take over from Joh as the root of that
subtree).
Solution 2 is to mark data Joh as deleted so that the data no longer exists but it can maintain its action
as an index for that part of the tree so that the subtree can be correctly negotiated.
Retrieval
The algorithm for this is:
Stacks
Insertion
Fig. 3.4.h.4 shows a stack and its head pointer. Remember, a stack is a last-in-first-out (LIFO) data
structure. If we are to insert an item into a stack we must first check that the stack is not full. Having
done this we shall increment the pointer and then insert the new data item into the cell pointed to by
the stack pointer. This method assumes that the cells are numbered from 1 upwards and that, when
the stack is empty, the pointer is zero.
Page 25 of 40
The algorithm for insertion is:
When an item is deleted from a stack, the item's value is copied and the stack pointer is moved down
one cell. The data itself is not deleted. This time, we must check that the stack is not empty before
trying to delete an item.
These are the only two operations you can perform on a stack.
Queues
Fig. 3.4.h.5 shows a queue and its head and tail pointers. Remember, a queue is a first-in-first-out (FIFO)
data structure. If we are to insert an item into a queue we must first check that the stack is not full.
Having done this we shall increment the pointer and then insert the new data item into the cell pointed
to by the head pointer. This method assumes that the cells are numbered from 1 upwards and that,
when the queue is empty, the two pointers point to the same cell.
Page 26 of 40
The algorithm for insertion is:
Before trying to delete an item, we must check to see that the queue is not empty. Using the
representation above, this will occur when the head and tail pointers point to the same cell.
These are the only two operations that can be performed on a queue.
Hash Table
A hash table or a hash map is a data structure that associates keys with values. The primary operation it
supports efficiently is a lookup: given a key (e.g. a person’s name), find the corresponding value (e.g. that
person’s telephone number). It works by transforming the key using a hash function into a hash, a
number that the hash table uses to locate the desired value.
Page 27 of 40
Insertion
In a hash table, each slot either contains a key or NIL (if the slot is empty) and if the slot is empty, then
you can insert your data item in that slot. If the hash table is searched until the end, and no empty slots
are found, then the algorithm will return “hash table full”
hash_insert (T, k) i := 0
repeat j := h(k, i)
if T[j] = NIL
then T[j] := k
else I := i+ 1 until i = m
error “hash table overflow”
For different searching and sorting algorithms, the logic behind their functioning differs. Some
algorithms can return the answer in less number of iterations than compared to other algorithms.
If we compare the Binary search to the linear search, it should be quite obvious by now that the Binary
search takes fewer iterations to return the value being searched for. However, as mentioned before,
the Linear search is very easy to implement which means that it does not take up a lot of computer
memory for its functioning unlike the Binary search. This is the compromise that you have to make
for stronger algorithms. Those which take fewer iterations (take less time to return answer) are more
likely to consume more computer memory and vice versa…
Page 28 of 40
19.2 Recursions
Recursion is a method where the solution to a problem depends on solutions to smaller instances of the
same problem (as opposed to iteration). It is when a function or procedure contains a call to itself or when
you define a subroutine in terms of itself. The approach can be applied to many types of problems, and
recursion is one of the central ideas of computer science.
When we write a method for solving a particular problem, one of the basic design techniques is to break
the task into smaller subtasks. For example, the problem of adding (or multiplying) N consecutive integers
can be reduced to a problem of adding (or multiplying) N – 1 consecutive integers:
For example, if N = 9 then you would have to add 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9. OR you could simply do
9
+ (1 + 2 + …… + 8).
Therefore, if we introduce a method sum R(n) or multiply R(n) that adds (or multiplies) integers from 1 to n,
then the above arithmetic’s can be rewritten as:
Important point to keep in mind for recursion is that it is called to do “part” of the work. If it is called to
do “all” the work, the result would be an infinite recursion (equivalent to an infinite loop). The recursive
function should run until all the work is:
Page 34 of 40
Let’s take an example of the factorial function of a positive integer n, written n!, is the product of all
the positive integers from 1 up to and including n. Thus, we have:
1! = 1
2! = 1 * 2 = 2
3! = 1 * 2 * 3 = 6
4! = 1 * 2 * 3 * 4 = 24
Etc.
Note that for example, 4! = 1 * 2 * 3 * 4 = (1 * 2 * 3) * 4 = 3! * 4, and in general n! = (n - 1)! * n.
Here is a function to calculate the factorial of a number (in Pascal):
01 FUNCTION Factorial(n)
02 IF n = 1 THEN
03 RETURN 1
04 ELSE
05 RETURN n * Factorial(n – 1)
06 END IF
07 END FUNCTION
Note that the stopping condition in the above code is IF n = 1 and the recursion happens on line 5.
Page 35 of 40
Fibonacci number example (pronounced Fibonachy)
Another good example is a method to calculate the Fibonacci numbers. By definition, the first two Fibonacci
numbers are 0 and 1, and each subsequent number is the sum of the previous two:
For example, take the sixth number, 5. This is the sum of the fifth number, 3, and the fourth number 2. In
mathematical terms, the sequence FRn Rof Fibonacci numbers is defined by the recursive statement.
The Fibonacci sequence can be Fn = Fn-1 + Fn-2 defined in a programming language too:
Page 36 of 40
Iteration vs Recursion
The best answer to this question could simply be, if you find it useful to use recursion in the problem. A
rule of thumb is to use recursion when you’re processing recursively defined data structures. If you try to
evaluate an arithmetic expression, for example, parenthesis may be used to enclose a “sub expression”
which must be evaluated first, and is an expression in its own right. The only reasonable way to do this is
to write a recursive expression routine; loops alone do not suffice.
On the other hand, it takes up a large amount of computer resources storing the return addresses and states.
Page 37 of 40
Recursion & Stacks
Most compilers implement recursion using stacks.
When a method is called in the main section of the code, the complier pushes the arguments to the
method and the return address on the stack, then transfers the control to the method.
When the method returns, it pops these values off the stack.
The arguments disappear and the control return to the return address and the main section of the code
continues to executes
Suppose you want to build a truth table and trace the execution for factorial (4). How do we do it using
stacks?
Page 38 of 40
Let’s build a trace table and see what happens. This trace table will be different from the ones that
you have built before as we are going to have to use a stack.
All is going well so far until we get to line 3. Now what do we do? We’ll soon have two values of n, one
for Function call 1 and one for Function call 2. Using the trace table as a stack (with the bottom of the
stack at the top and the top of the stack at the bottom) we’ll save all the data about the function call
including its value of n and make note of what line we need to return to when we have finished with
factorial(3).
We now have a similar situation to before, let's store the return address and go to factorial (2).
Now we have another problem, we have found an end to the factorial (1). What line do we go to next?
As we are treating our trace table as a stack we'll just pop the previous value off the top and look at
the last function call we stored away, that is function call 3, factorial(2), and we even know what line
to return to, line 3:
We know that factorial (1) = 1 from the previous returned value. Therefore factorial (2) returns 2 * 1 = 2
Page 39 of 40
Again we'll pop the last function call from the stack leaving us with function call 2, factorial (3) and line 3.
We know that factorial (2) = 2 from the previous returned value. Therefore factorial (3) returns 3 * 2 = 6
We reach the end of function call 1. But where do we go now? There is nothing left on the stack and
we have finished the code. Therefore the result is 24.
Page 40 of 40
19 Algorithms
May/June 2015.P31/P32
4 (a) briefly describe the operation of a stack data structure. [1]
High level language programs make extensive use of subroutines. A stack is used to store data about each
subroutine call.
The data are the return address, the register contents and the values of all local variables. A student
project is to simulate the saving and retrieval of the data for subroutine calls.
The student simplifies this for their project and will store on the stack only the return addresses.
The stack is implemented using the following data structure and variables.
Page 1 of 22
(c) The diagram shows the stack after the first procedure call at line 172.
(i) Complete the diagram to show the contents of the stack and the value of TOSafter each change. [5]
(ii) The student uses the procedure Push Address o tsimulate adding a return address to the stack.
The incomplete pseudo code for the procedure Push Address sishown below.
Using the given variables, fill in the missing pseudo code.
PROCEDURE PushAddress
IF TOS = 100
THEN
OUTPUT "……………………………………………………………………………………………………………………………………"
ELSE
INPUT ……………………………………………………………………………………………………………………………………….
TOS ← …………………………………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………………… ← NewAddress
END IF
END PROCEDURE [4]
Page 2 of 22
(c) The student uses the procedure PopAddress to simulate retrieving a return address from the stack.
Complete the pseudo code for this PopAddress procedure. [2]
PROCEDURE PopAddress
IF ……………………………………………………………………………………………………………………………………………
THEN
OUTPUT "There are no current procedure calls"
ELSE
OUTPUT "Address" Stack[TOS]
………………………………………………………………………………………………………………………………………
END IF
END PROCEDURE
Page 3 of 22
May/June 2015.P33
4 (a) Describe the operation of a stack data structure. [1]
A stack data structure is used to control the adding and removal of animal names.
The stack is implemented using the following data structure and variables.
(b) Complete the pseudo code procedure below to initialize the stack. [2]
PROCEDURE InitializeStack
FOR Index ← 0 to 99
Animal[…………………………..…………………………………………………………………………………………….…….]""
END FOR
StackPointer ← ……………………………………………………………………………………………………………………………...
END PROCEDURE
(c) The diagram shows the state of the stack after the following operations:
Page 4 of 22
A new value APE was added.
Animal [3]
StackPointer – 1 [2]
(ii) Adding a value to the stack is done with a procedure Push. [4]
Shown below is the incomplete pseudo code for procedure Push.
Using the variables given, fill in the missing pseudo code.
PROCEDURE Push
IF ………………………………………………………………………………………………………………………………………………………………
THEN
OUTPUT "REFUSED – stack is full"
ELSE
INPUT ……………………………………………………………………………….………………………………………………………………
StackPointer ← ………………………………………………………………………………………………………………….
…………………………………………………………………………………………………………..← NewAnimal
END IF
END PROCEDURE
(d) Removal of a value is implemented with a procedure Pop. Write pseudo code for the procedure Pop.
PROCEDURE Pop
ENDPROCEDURE [5]
Page 5 of 22
Oct/Nov 2015.P31/P33
5 (a) A dataset of city names is to be organized as an ordered binary tree. The city names below join the
binary tree in the order shown:
PLYMOUTH, MUMBAI, DHAKA, SINGAPORE, NEW YORK, ROTTERDAM and TORONTO.
State the number of leaf nodes for the tree drawn in part (i). [1]
(b) The binary tree is implemented in a high-level language using a number of data structures
and one variable: [1]
Page 6 of 22
(b) An algorithm is designed in pseudo code to search the binary tree for a particular city. The algorithm
uses the additional variables below:
INPUT ………………………………………………………………………………………………………………………………………………………
IsFound ← FALSE
Current ← RootPtr
REPEAT
IF City [Current] =………………………………………………………………………………………………………………………………………
THEN
// found
OUTPUT “FOUND”
…………………………………………………………………………………………………………………………………………………………………
ELSE
IF SearchCity > City[Current]
THEN
// move right
…………………………………………………………………………………………………………………………………………………………………
ELSE
Current ← LeftPtr[Current]
ENDIF
ENDIF
UNTIL Current = 0 OR ………………………………………………………………..…………………………………………………………
IF …………………………………………………………………………………………………………………………………………………
THEN
OUTPUT SearchCity "Not Found"
ENDIF
Page 7 of 22
Oct/Nov 2015.P32
Four more food names join the binary tree in the order shown:
SCONES, RICE, BREAD, COUSCOUS
(b) The binary tree is implemented in a high-level language using a number of data structures and one
variable:
Page 8 of 22
A new dataset of food names is used as test data: [4]
MELON, BEETROOT, TURNIP, APPLE, PARSNIP, SWEDE, QUINCE
Complete the diagram below showing the contents of the arrays and the root pointer variable.
(c) An algorithm is designed in pseudo code to search the binary tree for a particular food name. The
algorithm uses the additional variables below:
Page 9 of 22
//found
OUTPUT "Found"
……………………………………………………………………………………………………………………………………………………..
ELSE
IF SearchFood < Food[Current]
THEN
// move left
Current ← LeftPtr[Current]
ELSE
END IF
END IF
…………………………………………………………………………………………………………………………………………………………
UNTIL IsFound = TRUE OR …………………………………………………………………………………………………………
IF IsFound = FALSE
THEN
OUTPUT SearchFood "Not Found"
END IF
(d) (i) The dataset used in part (b) was: [2]
MELON, BEETROOT, TURNIP, APPLE, PARSNIP, SWEDE, QUINCE
Draw the binary tree.
A well-balanced tree has approximately the same number of nodes in the left and right sub trees.
(ii) State whether or not this is a well-balanced tree. [1]
Page 10 of 22
May/June 2015.P41/P42
(i) Complete the pseudo code algorithm for an insertion sort. [7]
ENDFOR
(ii) A special case is when NameList is already in order. The algorithm in part (a)(i) is applied to this special
case. Explain how many iterations are carried out for each of the loops. [3]
FOR Pointer ← 1 TO 9
THEN
Temp ← NameList[Pointer]
NameList[Pointer] ← NameList[Pointer + 1]
NameList[Pointer + 1] ← Temp
END IF
END FOR
END FOR
Page 11 of 22
(i) As in part (a)(ii), a special case is when NameList is already in order. The algorithm in part (b)
is applied to this special case.
Explain how many iterations are carried out for each of the loops. [2]
(ii) Rewrite the algorithm in part (b), using pseudo code, to reduce the number of unnecessary
comparisons. Use the same variable names where appropriate. [5]
Page 12 of 22
May/June 2015.P43
5 A stack Abstract Data Type (ADT) has these associated operations:
Create Stack
Add item to stack (push)
Remove item from stack (pop)
(a) There is one pointer: the top of stack pointer, which points to the last item added to the stack. Draw
a diagram to show the final state of the stack after the following operations are carried out. [3]
CreateStack
Push("Ali")
Push("Jack")
Pop Push("Ben")
Push("Ahmed")
Pop
Push("Jatinder")
Add appropriate labels to the diagram to show the final state of the stack. Use the space on the left as a
workspace. Show your final answer in the node shapes on the right:
TYPE Node
DECLARE Name: STRING
DECLARE Pointer: INTEGER
ENDTYPE
The statement
DECLARE Stack: ARRAY[1:10] OF Node reserves space for 10 nodes in array Stack.
Page 13 of 22
(i) The CreateStackoperation links all nodes and initializes the TopOfStackPointerand [4]
Free Pointer.
Complete the diagram to show the value of all pointers after CreateStackhas been executed.
(ii) The algorithm for adding a name to the stack is written, using pseudo code, as a procedure with the
header
PROCEDURE Push (NewName)
Where NewName is the new name to be added to the stack. The procedure uses the variables as
shown in the identifier table.
Page 14 of 22
PROCEDURE Push(BYVALUE NewName : STRING)
// Report error if no free nodes
remaining
IF FreePointer = 0
THEN
Report Error
ELSE
Stack[FreePointer].Name ← NewName
// take a temporary copy and
TempPointer ← FreePointer
FreePointer ← Stack[FreePointer].Pointer
Stack[TempPointer].Pointer ← TopOfStackPointer
// adjust TopOfStackPointer to current node
TopOfStackPointer ← TempPointer
ENDIF
ENDPROCEDURE
Page 15 of 22
Complete the pseudo code for the procedure Pop. Use the variables listed in the identifier table. [5]
PROCEDURE Pop()
…………………………………………………………………………………………………………………………………………………
…………………………………………………………………………………………………………………………………………………
…………………………………………………………………………………………………………………………………………………
………………………………………………………………………………...……………………………………………………
………………………………………………………………………………………………………………………………………………
// update the top of stack pointer
………………………………………………………………………………………………………………………………………………
// link released node to free list
………………………………………………………………………………………………………………………………………………
………………………………………………………………………………………………………………………………………………
……………………………………………………………………………………………………………………………………………
ENDPROCEDURE
Page 16 of 22
May/June 2018.P41/43
01 MaxIndex ← 20
02 NumberItems ← …………………………………………………………………………………………….......………………………………
03 FOR Outer ← 1 TO …………………………………………………………………………………………………………………...............
04 FOR Inner ← 1 TO NumberItems
05 IF ItemList[Inner] > …………………………………………………………………………………………………………………….
06 THEN
07 Temp ← ItemList [……………………………………………………………………………………………..……………..]
08 ItemList[Inner] ← ItemList [……………………………………………………………………………………………...]
09 ItemList[Inner + 1] ← ………………………………………………………………………………………………………...
10 END IF
11 END FOR
12 NumberItems ← …………………………………..…………………………………………….......………………………………
13 END FOR
Page 17 of 22