0% found this document useful (0 votes)
321 views9 pages

Caie A2 Level Computer Science 9618 Practical v4

The document summarizes sorting and searching algorithms including linear search, binary search, bubble sort, insertion sort, and abstract data types including stacks and queues. Key algorithms and data structures covered include binary search, bubble sort, insertion sort, stacks using LIFO and applications such as interrupt handling and procedure calling, and queues using FIFO.

Uploaded by

j53846004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
321 views9 pages

Caie A2 Level Computer Science 9618 Practical v4

The document summarizes sorting and searching algorithms including linear search, binary search, bubble sort, insertion sort, and abstract data types including stacks and queues. Key algorithms and data structures covered include binary search, bubble sort, insertion sort, stacks using LIFO and applications such as interrupt handling and procedure calling, and queues using FIFO.

Uploaded by

j53846004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

ZNOTES.

ORG

UPDATED TO 2024-2025 SYLLABUS

CAIE A2 LEVEL
COMPUTER
SCIENCE
SUMMARIZED NOTES ON THE PRACTICAL SYLLABUS
CAIE A2 LEVEL COMPUTER SCIENCE

def binary_search(arr, target): low, high = 0, len(arr) - 1


while low <= high: mid = (low + high) // 2 mid_element =
1. Sorting and Searching arr[mid]

Algorithms if mid_element == target:


return f"Item {target} found at index {mid}.
Part of the Computational Thinking and Problem-Solving elif mid_element < target:
Chapter low = mid + 1
else:
high = mid - 1
1.1. Linear Search
return f"Item {target} not found in the array.
The user is asked to enter an item they want to find in an
array.
All elements of an array are searched one by one until the
1.3. Bubble Sort
item the user entered is found.
When an item is found, the algorithm outputs an How Does It Work?
appropriate message saying that the item is found and
Bubble sort compares adjacent elements in the list/array.
which index/location the item is at.
They are swapped if the elements are in the wrong order
If the particular item is not found, the algorithm outputs
(according to the desired sorting).
an appropriate message saying that the item is not found.
The algorithm iterates through the array multiple times in
The linear search algorithm has a Big O notion of O(n). passes.
On each pass, the largest unsorted element "bubbles up"
Python Code to its correct position at the end of the array.
The process is repeated until the entire array is sorted.

Python Code

def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
1.2. Binary Search for i in range(n):
# Last i elements are already sorted, so we don't need t
The necessary condition for a binary search is that the
for j in range(0, n-i-1):
list/array being searched must be ordered/sorted.
# Swap if the element found is greater than the next
if arr[j] > arr[j+1]:
How does It Work?
arr[j], arr[j+1] = arr[j+1], arr[j]
The middle item/index of the list is found In the worst case, it has a time complexity of O(n^2), where n
Item at the middle of the list is compared to item user
is the number of elements in the array.
inputs
if the item in the middle of the list is the same as the item
that item user inputs, a message saying “item found” is 1.4. Insertion Sort
output.
If the item is greater than what the user inputted, all the How Does It Work?
items at the index lower than the middle index are
The algorithm starts with the assumption that the first
discarded.
element in the array is already sorted.
If the item is lower than what the user inputted, all the
items at the index greater than the middle index are It then compares the next element with the sorted portion
discarded. of the array.
The above steps are repeated until the item searched for If the next element is smaller, it shifts the larger elements
is found to the right until it finds the correct position for the next
If one item is left in the list and it is not the item searched element and inserts it there.
The sorted portion of the array grows with each iteration
for, a message saying “item not found” is outputted.
until the entire array is sorted.
The binary search algorithm has a Big O notion of O(log n). The process is repeated until all elements are in their
The log is of base 2. correct positions.

Python Code Python Code

WWW.ZNOTES.ORG
CAIE A2 LEVEL COMPUTER SCIENCE

def insertion_sort(arr):
for i in range(1, len(arr)): OUTPUT “Stack is full”
key = arr[i]
j=i-1 ELSE

# Move elements of arr[0..i-1] that are greater than key to TopOfStack


one position= TopOfStack
ahead of their
+ 1 current position
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j] MyStack[TopOfStack] = NewItem
j -= 1
ENDIF
arr[j + 1] = key
ENDPROCEDURE
In the worst case, it has a time complexity of O(n^2), where n
is the number of elements in the array. Use of Stacks:
Insertion sort is efficient for small datasets or partially sorted
datasets. Interrupt Handling
The contents of the register and the PC are saved and
put on the stack when the interrupt is detected
2. Abstract Data Types (ADTs) The return addresses are saved onto the stack as well
Retrieve the return addresses and restore the register
Part of the Computational Thinking and Problem-Solving contents from the stack once the interrupt has been
Chapter serviced
Evaluating mathematical expressions held in Reverse
Polish Notation
2.1. Stacks Procedure Calling
Every time a new call is made, the return address
Stack – an ADT where items can be popped or pushed
must be stored
from the top of the stack only
Return addresses are recalled in the order ‘the last
LIFO – Last In First Out data structure
one stored will be the first to be recalled.’
If there are too many nested calls, then stack overflow
Popping

2.2. Queues
PROCEDURE PopFromStack
Queue: an ADT where new elements are added at the end
IF TopOfStack = -1 of the queue, and elements leave from the start of the
queue
THEN FIFO: First In, First Out Data structure
Creating a Circular Queue:
OUTPUT “Stack is already empty”
PROCEDURE Initialise
ELSE
Front = 1
OUTPUT MyStack[ TopOfStack ] “is popped”
Rear = 6
TopOfStack ← TopOfStack – 1
NumberInQueue := 0
ENDIF
END PROCEDURE
ENDPROCEDURE
To add an Element to the Queue:

Pushing PROCEDURE EnQueue

IF NumberInQueue == 6
PROCEDURE PushToStack
THEN Write (“Queue overflow”)
IF TopOfStack = MaxStackSize
ELSE
THEN

WWW.ZNOTES.ORG
CAIE A2 LEVEL COMPUTER SCIENCE

IF Rear == 6 It can be represented as two 1-D arrays - a string array


for data values and an integer array for pointer values
THEN Rear = 1 Creating a Linked list →Setting values of pointers in the
free list and empty data linked list
ELSE Rear = Rear + 1

ENDIF FOR Index ← 1 TO 49

Q[Rear] = NewItem NameList[Index].Pointer ← Index + 1

NumberInQueue =NumberInQueue +1 ENDFOR

ENDIF NameList[50].Pointer ← 0

ENDPROCEDURE HeadPointer ← 0

FreePointer ← 1
The front of the queue is accessed through the pointer
Front.
To add an element to the queue, the pointers have to be A user-defined record type should first be created to
followed until the node containing the pointer of 0 is represent a node’s data and pointer:
reached → the end of the queue, and this pointer is then
changed to point to the new node.
In some implementations, two pointers are kept: 1 to the
front and 1 to the rear. This saves traversing the whole
queue when a new element is to be added.
To Remove an Item from the Queue

PROCEDURE DeQueue

IF NumberInQueue == 0

THEN Write (“Queue empty”) Inserting into a Linked List

ELSE

NewItem = Q[Front]

NumberInQueue = NumberInQueue – 1

IF Front ==6

THEN Front = 1

ELSE

Front = Front + 1

ENDIF

ENDIF

END PROCEDURE

Items may only be removed from the front of the list and
added to the end of the list

2.3. Linked Lists

WWW.ZNOTES.ORG
CAIE A2 LEVEL COMPUTER SCIENCE

Searching a Linked List

2.4. Binary Search


Dynamic Data structure: can match the size of data
requirement.
Takes memory from the heap as required and returns
memory as required, following a node deletion
Deleting an Item from a Linked List
An ADT consisting of nodes arranged hierarchically,
Use a Boolean value to know when an item has been
starting with a root node
found and deleted (initially false)
Usually implemented using three 1-D arrays
Use a pointer (CurrentPointer) to go through each node’s
A node can have no more than two descendants in a
address
binary tree.
If the new item is found in the header:
1. Set head pointer to pointer of node at
CurrentPointer
2. Set the pointer on node at CurrentPointer to free
pointer
3. The free pointer points to CurrentPointer
4. Set the Boolean value to True
Otherwise:
1. Search for an item when the end of the linked list is
not reached and a Boolean value is false.
1. Use a Previous Pointer to keep track of the
node located just before the one deleted
2. CurrentPointer points to the next node’s
address
3. If data in the node at CurrentPointer
matches SearchItem
Set the pointer of the node at
PreviousPointer to the pointer of the
A binary tree node is like a linked list node but with two
node at CurrentPointer
pointers, LeftChild and RightChild.
Set the pointer of the node at
Binary trees can be used in many ways. One use is to hold
CurrentPointer to FreePointer
an ordered set of data. In an ordered binary tree, all items
Set FreePointer to CurrentPointer
to the root's left will have a smaller key than those on the
Boolean value becomes true
root's right. This applies equally to all the sub-trees.
If the Boolean value is false
Tree algorithms are invariably recursive.
1. Inform the user that the item to be deleted has not
To insert data into an ordered tree, the following
been found
recursive algorithm can be used:

WWW.ZNOTES.ORG
CAIE A2 LEVEL COMPUTER SCIENCE

PROCEDURE insert(Tree, Item)


IF Tree is empty THEN create new tree with Item as the root.
ELSE IF Item < Root
THEN insert(Left sub-tree of Tree, Item)
ELSE insert(Right sub-tree of Tree, Item)
ENDIF
ENDIF
ENDPROCEDURE

Another common use of a binary tree is to hold an


algebraic expression, for example X + Y * 2
It could be stored as:

3. Recursion
Part of the Computational Thinking and Problem-Solving
Chapter

3.1. Essential Features of a Recursion


Must have a base case/stopping condition
Binary Tree
Must have a general case which calls itself (recursively) //
START at Root Node Defined in terms of itself
The general case should be changing its state and move
toward the base case
REPEAT
Unwinding occurs once the base case is reached.
IF WantedItem = ThisItem
3.2. Advantages and Disadvantages of a
THEN Found = TRUE
Recursion
ELSE
Advantages Disadvantages

IF WantedItem > ThisItem Less efficient in terms of


Can produce simpler, more
computer time and storage
natural solutions to a problem
THEN Follow Right Pointer space
A lot more storage space is
ELSE Follow Left Pointer used to store return
addresses and states.
UNTIL Found or Null Pointer Encountered This could lead to infinite
recursion.

3.3. How A Compiler Translates


Recursive Programming Code
Before the procedure call is executed, the current state of the
registers/local variables is saved onto a stack.

When returning from a procedure call, the registers/local


variables are re-instated on the stack
When the stopping condition/base case is met, the
algorithm unwinds the last set of values that are taken off
the stack (in reverse order)

WWW.ZNOTES.ORG
CAIE A2 LEVEL COMPUTER SCIENCE

When you create an instance of the class, the constructor


4. Object-Oriented is invoked automatically to set the object's initial state.
This ensures that objects are created in a valid and
Programming consistent state.

Part of the Further Programming Chapter 4.3. Defining Classes and Methods
4.1. Key Terms & Definitions • To define a class in Python, use the class keyword followed
by the class name.
Objects: Instances of classes representing real-world • Inside the class, you can define attributes (variables) and
entities. methods (functions) that belong to the class.
Properties/Attributes: The data items/attributes and the Here's a simple example of defining a class called Person
data types // characteristics defined in a class. with attributes and methods as shown below:
Methods: the procedures/ functions / programmed
instructions in a class that act on the
properties/attributes.
Classes: Blueprint for creating objects with shared
attributes and methods.
Inheritance: It is a mechanism for creating a new class
based on an existing one, inheriting its attributes and
methods. Through inheritance, attributes contained in one
class (parent class) are made available to / reused by
another class (child class).
Polymorphism: Ability to use different classes through a
common interface. It allows the same method to take on
4.4. Get and Set Methods
different behaviours depending on which class is
These methods are used to access/change attributes set to
instantiated. These methods can be redefined for derived
be private in a class. These methods are decelerated inside
classes.
the class.
Containment (Aggregation): Combining multiple objects to
create a more complex object.
Encapsulation: Hiding the internal details of a class from
the outside.
Getters and Setters: Methods for accessing and modifying
object attributes. Get methods/Getters are used to access
attributes, while set methods/setters are used to modify
object attributes.
Instances: Individual objects created from a class.

4.2. Constructor
Constructors are functions that are used for initializing the 4.5. Inheritance
attributes/Properties of a class.
• Inheritance is a fundamental concept in OOP that allows you
A constructor in Object-Oriented Programming (OOP) is a to create a new class (a derived or child class) based on an
special method within a class that is automatically called existing class (a base or parent class).
when an object of that class is created. • The child class inherits the attributes and methods of the
Its primary purpose is to initialize the object's attributes or parent class and can also add new attributes and methods or
perform setup actions. override the ones inherited.
In Python, the constructor is typically named init and takes In the context of the Person class, Inheritance would involve
the self parameter, which refers to the created object. creating a child class, such as a Student or Employee, that
Inside the constructor, you initialize the object's attributes. inherits attributes and methods from the Person class. For
For example: example, a Student class could inherit the name and age
attributes and the get_name method from the Person class.

Polymorphism

WWW.ZNOTES.ORG
CAIE A2 LEVEL COMPUTER SCIENCE

• Polymorphism is the ability of different classes to be treated leading underscore). This indicates that __name it should not
as instances of a common base class. It allows objects of be accessed directly from outside the class. Instead, you
different classes to be used interchangeably if they provide a controlled interface through the get_name and
implement the same methods or interface. set_name methods, ensuring that name changes are
• Polymorphism promotes flexibility and extensibility in your validated and controlled.
code. Below is a brief code example illustrating how inheritance,
In the context of the Person class, Polymorphism could be polymorphism, and encapsulation could be applied to the
applied when you have different types of persons, such as Person class:
students, employees, and teachers, each having a get_name
method. You can call get_name on instances of these
different classes without knowing their specific type, as long
as they all have a get_name method.

Encapsulation

• Encapsulation is the practice of hiding the internal details of


a class and providing a controlled interface to access and
modify the class's attributes. • In the example above, the Student class inherits from the
• This helps maintain the integrity and consistency of the Person class, demonstrating the concept of inheritance. •
object's state by controlling how data is accessed and Both classes can be treated interchangeably when calling the
modified. get_name method, showing polymorphism. • Encapsulation
In the context of the Person class, Encapsulation is applied by is maintained by controlling access to the name attribute
making the name attribute private (by convention, using a through getter and setter methods.

WWW.ZNOTES.ORG
CAIE A2 LEVEL
Computer Science

Copyright 2024 by ZNotes


These notes have been created by Ashmit Bhola for the 2024-2025 syllabus
This website and its content is copyright of ZNotes Foundation - © ZNotes Foundation 2024. All rights reserved.
The document contains images and excerpts of text from educational resources available on the internet and
printed books. If you are the owner of such media, test or visual, utilized in this document and do not accept its
usage then we urge you to contact us and we would immediately replace said media.
No part of this document may be copied or re-uploaded to another website without the express, written
permission of the copyright owner. Under no conditions may this document be distributed under the name of
false author(s) or sold for financial gain; the document is solely meant for educational purposes and it is to remain
a property available to all at no cost. It is current freely available from the website www.znotes.org
This work is licensed under a Creative Commons Attribution-NonCommerical-ShareAlike 4.0 International License.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy