TeM - SWDDA401 - Data Structure and Algorithm Fundementals
TeM - SWDDA401 - Data Structure and Algorithm Fundementals
SWDDA401
SOFTWARE
DEVELOMENT
Data Structure
and
Algorithm
Fundamentals
TRAINEE'S MANUAL
October, 2024
DATA STRUCTURE AND ALGORITM
FUNDAMENTALS
ii |D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e M a n u a l
2024
AUTHOR’S NOTE PAGE (COPYRIGHT)
The competent development body of this manual is Rwanda TVET Board ©, reproduce
with permission.
● This work has been produced initially with the Rwanda TVET Board with the support
from KOICA through TQUM Project
● This work has copyright, but permission is given to all the Administrative and
Academic Staff of the RTB and TVET Schools to make copies by photocopying or
other duplicating processes for use at their own workplaces.
● This permission does not extend to making of copies for use outside the immediate
environment for which they are made, nor making copies for hire or resale to third
parties.
● The views expressed in this version of the work do not necessarily represent the
views of RTB. The competent body does not give warranty nor accept any liability
● RTB owns the copyright to the trainee and trainer’s manuals. Training providers
may reproduce these training manuals in part or in full for training purposes only.
Acknowledgment of RTB copyright must be included on any reproductions. Any
other use of the manuals must be referred to the RTB.
The publisher would like to thank the following for their assistance in the elaboration of
this training manual:
Rwanda TVET Board (RTB) extends its appreciation to all parties who contributed to the
development of the trainer’s and trainee’s manuals for the TVET Certificate IV in Software
Development, specifically for the module " SWDDA401: Data Structure and Algorithm
Fundamentals."
We extend our gratitude to KOICA Rwanda for its contribution to the development of
these training manuals and for its ongoing support of the TVET system in Rwanda
We extend our gratitude to the TQUM Project for its financial and technical support in the
development of these training manuals.
We would also like to acknowledge the valuable contributions of all TVET trainers and
industry practitioners in the development of this training manual.
The management of Rwanda TVET Board extends its appreciation to both its staff and the
staff of the TQUM Project for their efforts in coordinating these activities.
PRODUCTION TEAM
Authoring and Review
ISHIMWE Gilbert
NIZEYIMANA Martin
Validation
KWIZERA Olivier
SEKABANZA Jean de la Paix
Key Competencies for Learning Outcome 2: Apply Data Structure ------------------------------------------- 106
Indicative content 2.1: Identification of Data Structure Concepts -------------------------------------------- 108
Indicative content 2.2: Application of Linear Data Structures and their Operations --------------------- 125
Indicative content 2.3: Application of Non-Linear Data Structures and their Operations --------------- 136
Learning outcome 2 end assessment --------------------------------------------------------------------------------- 144
References ------------------------------------------------------------------------------------------------------------------ 146
Key Competencies for Learning Outcome 3: Implement Algorithm using JavaScript -------------------- 148
Indicative content 3.1: Development of JavaScript Source Code ---------------------------------------------- 150
Indicative content 3.2: Run JavaScript Source Codes------------------------------------------------------------- 203
Indicative content 3.3: Test Time and Space Complexity -------------------------------------------------------- 208
Learning outcome 3 end assessment --------------------------------------------------------------------------------- 214
References ------------------------------------------------------------------------------------------------------------------ 216
viii|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
INTRODUCTION
This trainee's manual includes all the knowledge and skills required in TVET Certificate IV in
Software Development, specifically for the module of "Data Structure and Algorithm
Fundamentals". Trainees enrolled in this module will engage in practical activities designed
to develop and enhance their competencies. The development of this training manual
followed the Competency-Based Training and Assessment (CBT/A) approach, offering ample
practical opportunities that mirror real-life situations.
The trainee's manual is organized into Learning Outcomes, which is broken down into
indicative content that includes both theoretical and practical activities. It provides detailed
information on the key competencies required for each learning outcome, along with the
objectives to be achieved.
As a trainee, you will start by addressing questions related to the activities, which are
designed to foster critical thinking and guide you towards practical applications in the labour
market. The manual also provides essential information, including learning hours, required
materials, and key tasks to complete throughout the learning process.
All activities included in this training manual are designed to facilitate both individual and
group work. After completing the activities, you will conduct a formative assessment, referred
to as the end learning outcome assessment. Ensure that you thoroughly review the key
readings and the 'Points to Remember' section.
By the end of the learning outcome, the trainees will be able to:
1. Describe correctly number system based on number system types
[Link] correctly Number systems according to the base conversion
methods
3. Describe well Logic gates and expressions based on Boolean algebra
4. Apply effectively Data types according to their intended use
5. Apply appropriately Operators based on datatype
6. Write Algorithm properly based on problem to be solved
7. Draw properly program flowchart based on best practice
Resources
Duration: 6 hrs
● Addition: Binary addition follows the same principles as decimal addition, but
with a base of 2. The possible sums are:
0+0=0
1+0=1
1 + 1 = 10 (which is 2 in decimal, so carry 1)
● Addition: Similar rules apply as in decimal, but when sums reach 8, they roll over
(carry) to the next higher place.
● Subtraction: Borrowing in octal occurs when subtracting a larger number from
a smaller one in a given column.
● Multiplication and Division: Follows the rules of base 8, with operations often
facilitated by conversion from or to decimal or binary.
3. Decimal Arithmetic (Base 10)
Decimal arithmetic is the standard system used in everyday life and most traditional
mathematics. Operations in decimal involve the digits 0 through 9.
● Addition: Similar to decimal and binary, with sums that exceed 15 rolling over
(carry) to the next higher place.
● Subtraction: Requires borrowing when a larger hexadecimal digit is subtracted
from a smaller one.
● Multiplication and Division: As with binary and octal, but using base 16 rules.
5. Conversions Between Number Bases
Conversions between different number bases are also important for various
applications, especially in computing and digital electronics. Understanding how to
convert between binary, octal, decimal, and hexadecimal systems is fundamental in
these fields.
3.2 Application
Task:
(157)10= (10011101)2
1.2. Binary to decimal
1. Write each value of the binary number times two, from right to left, write the
power of two starting from0
(10011101)2= (157)10
Then, the answer will be written from right to left like this: 62010 = (26C)16
(b) 11101001102 =( )16 Here we have to make (form) the groups of 4 digits each,
from right to left. If it is necessary, we add the zeros on the last group where the
bits are less than 4. Lastly, we translate every quadruple to its equivalent
hexadecimal.
The answer will be:
0011 1010 0110 = ( )16
3 A 6
= 3A616
Exercises
I. Answer the following questions
a) Convert 0010 0110 from base 2 to decimal
b) Convert 1010 from base 2 to base 10
c) Convert 1100 0110 from binary to base 10
III.
IV.
1. 1011001
2. 01001110
3. 11101.001
4. 00110111
5. 10101010
6. 011.11111
7. 10000000
8. 01010101
15|D a t a S t r u c t u r e and Algorithm Fundamentals–Trainee
Manual
9. 11001100
10. 00011001
After conversion share your findings with the researchers’ team, who will attempt to
interpret the message based on the converted numbers.
Duration: 6 hrs
NOT 5.
A Out 6.
1 0 7.
0 1 8.
AND A .B 9.
A B Out 10.
0 0 0 11.
0 1 0 12.
1 0 0 13.
1 1 1 14.
NAND 15.
A B Out 16.
0 0 1 17.
0 1 1 18.
XNOR 39.
A B Out 40.
0 0 1 41.
0 1 0 42.
1 0 0 43.
44.
1 1 1 45.
1. Logic gates are digital circuits that conduct logical operations on the input
provided to them and produce appropriate output.
2. To accomplish a specific logical process, universal gates are created by merging
two or more fundamental gates. Universal gates are NAND and NOR gates.
3. Because NOT gate is an inverter. As a result, if 0 is used as an input, the output
will be 1.
4. An inventor is also known as a NOT gate. The obtained output is the inverse of
the input.
Task:
b)
[Link] the following logic gate circuit into a Boolean expression, writing Boolean sub-
expressions next to each gate output in the diagram:
Summary
Q
(A + B).(A + C)
=
Q
A + (B.C) Identity AND law (A.1 = A)
=
4. ̅̅̅̅̅̅̅̅
(𝐴. 𝐵)+(A̅̅̅̅̅̅̅̅̅̅
+ ̅̅̅
B)
Using De Morgan’s Rule 6a (𝐴̅ + 𝐵̅ ) + ( 𝐴̅ + 𝐵)
Then apply rule 1a 𝐴̅ + 𝐴̅ = 𝐴̅
Which gives 𝐴̅ + 𝐵 + 𝐵̅ but Rule 1c makes this 𝐴̅ + 1
We can then apply rule 1e to give 𝐴̅ + 1 = 1
5. (𝑋 + 𝑌). (𝑋 + 𝑌̅)
Using distributive Rule 4b we get X + (Y + 𝑌̅)
Using Rule 1d this gives us X + 0
Rule 1f says that X + 0 = X
6. ̅̅̅̅̅̅̅̅̅̅̅̅̅
̅̅̅̅̅̅̅̅
𝐴̅ + (𝐵. 𝐴)
Reapplying De Morgan’s Law gives 𝐴̿ + 𝐵̿ , and using double negation (Rule 5) gives
A+B
7. 𝐴. 𝐵. 𝐶̅ + 𝐴. 𝐶̅
Using the distributive law 4a this gives A.(𝐵. 𝐶̅ + 𝐶̅ ))
We can then use the distributive rule again to give A.(𝐶̅ (𝐵 + 1))
Because of Rule 1e we get A.𝐶̅ (1))
The answer is therefore A.𝐶̅
8.𝐵. (𝐴 + 𝐴̅)
Using Rule 1c, B.(1) = B
9. A.B+B
Using distributive law B.(A+1)
2's complement
The 2's complement of binary number is obtained by adding 1 to the Least Significant
Bit (LSB) of 1's complement of the number.
2's complement = 1's complement + 1
Example of 2's Complement is as follows.
● Circuits
A logic circuit can be defined as an electrical circuit that executes logical operations
on one or more binary inputs to produce a single binary output.
They operate based on Boolean algebra principles, which are grounded in the truth
values true and false, often represented as 1 and 0, respectively.
Logic circuits are critical in CPU microarchitecture and cores to undertake tasks such
as computation, encoding, multiplexing, and memory interfacing. They also play a
significant role in developing hardware like ALUs (Arithmetic Logic Units).
Circuits enables computers to do more complex operations than they could
accomplish with just a single gate.
The smallest circuit is a chain of 2 logic gates.
Consider this circuit:
Answers:
i.
ii.
[Link] the following logic gate circuit into a Boolean expression, writing Boolean
sub-expressions next to each gate output in the diagram:
a)
b)
Solution:
Points to Remember
● A Logic gate is an essential component of digital circuits. It takes one or more binary
inputs and produces an output based on the logic rule it operates.
● There are 3 types of logic gates: Basic Gates :( OR, AND, and NOT Gates), Universal
Gates :( NAND, and NOR Gates) and Derived Gates: (XOR Gates, and XNOR Gates).
● In computer science, the role of logic circuits is fundamental and profound. They
form the core building blocks of digital systems and contribute to the functionality
of every type of digital device, from calculators and watches to powerful computer
processors and complex digital networks
● The procedure to detect output states using a truth table consists of the following
steps:
1. Create a truth table with a number of input columns equal to the number of inputs
in your logic circuit. Add one more column to denote the output.
2. The number of rows in the truth table would equal 2n, where n is the number of
inputs.
For example, if you have 2 inputs, you'll have 22=4 rows. Two zeros and two ones
3. Fill in the table with all possible combinations of inputs.
Duration: 6 hrs
Tasks:
1: Answer the following questions:
i. Discuss on the following terms as used in JavaScript:
a) Variable
b) Data types
• Variables
In JavaScript, Variable is a container for Storing Data. Also we can say that variable is a
memory zone used to store and manage data.
JavaScript Variables can be declared in 4 ways:
✓ Automatically
✓ Using var
✓ Using let
✓ Using const
In this first example, x, y, and z are undeclared variables.
They are automatically declared when first used:
Example
x = 5;
y = 6;
Primitive data types are predefined types of data, which are supported by the
programming language.
Primitive Data Types:
Number: Represents numeric values, both integers and floating-point
numbers.
Example: let age = 25; let pi = 3.14159;
String: Represents textual data, enclosed in single or double quotes.
Example: let name = "Alice"; let greeting = 'Hello, world!';
BigInt: Represents arbitrarily large integers (introduced in ES2020).
Example: let largeNumber = 9007199254740991n;
Boolean: Represents logical values, either true or false.
The data type that are derived from primary data types are known as non-
primitive data type.
Non-primitive data types are not defined by the programming language, but are
instead created by the programmer.
They are sometimes called “reference variables," or "object references," since
they reference a memory location, which stores the data.
NB: The non-primitive data types are used to store the group of values.
✓ Object: A collection of key-value pairs, used to store complex data structures.
Example: let person = { name: "John", age: 30 };
✓ Array: An ordered collection of values, accessed by numerical indices.
Example: let numbers = [1, 2, 3, 4, 5];
Is it a must to specify a data type in JavaScript?
No, it's not mandatory to explicitly specify data types when declaring variables in
JavaScript. Here's why:
JavaScript is dynamically typed:
✓ It infers the data type of a variable based on the value assigned to it at runtime.
✓ This means you can declare a variable without specifying a type, and its type
will be determined by the first value you assign to it.
The undefined type is a primitive type that has only one value undefined. By default,
when a variable is declared but not initialized, it is assigned the value of undefined.
Consider the following example:
let counter;
[Link](counter); // undefined
[Link](typeof counter); // undefinedCode language: JavaScript (javascript)
In this example, the counter is a variable. Since counter hasn’t been initialized, it is
assigned the value undefined. The type of counter is also undefined.
It’s important to note that the typeof operator also returns undefined when you call it
on a variable that hasn’t been declared:
[Link](typeof undeclaredVar); // undefinedCode language: JavaScript (javascript)
The null type is the second primitive data type that also has only one value null. For
example:
let obj = null;
[Link](typeof obj); // objectCode language: JavaScript (javascript)
The typeof null returns object is a known bug in JavaScript. A proposal to fix this was
proposed but rejected. The reason was the that fix would break a lot of existing sites.
JavaScript defines that null is equal to undefined as follows:
[Link](null == undefined); // trueCode language: JavaScript (javascript)
JavaScript uses the number type to represent both integer and floating-point numbers.
The following statement declares a variable and initializes its value with an integer:
let num = 100;Code language: JavaScript (javascript)
To represent a floating-point number, you include a decimal point followed by at least
one number. For example:
let price= 12.5;
let discount = 0.05;Code language: JavaScript (javascript)
The boolean type has two literal values: true and false in lowercase. The following
example declares two variables that hold the boolean values.
let inProgress = true;
let completed = false;
[Link](typeof completed); // booleanCode language: JavaScript (javascript)
JavaScript allows values of other types to be converted into boolean values of true or
false.
● Data types are primarily used in computer programming, in which variables are
created to store data. Each variable is assigned a data type that determines what
type of data the variable may contain.
Duration: 6 hrs
Task:
1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will
give "a10".
Example
The following code shows how to use arithmetic operators in JavaScript.
<html>
<body>
[Link]("a + b = ");
result = a + b;
[Link](result);
[Link](linebreak);
[Link]("a - b = ");
result = a - b;
[Link](result);
[Link](linebreak);
[Link]("a / b = ");
result = a / b;
[Link](result);
[Link](linebreak);
[Link]("a % b = ");
result = a % b;
[Link](result);
[Link](linebreak);
[Link]("a + b + c = ");
result = a + b + c;
[Link](result);
[Link](linebreak);
b = --b;
[Link]("--b = ");
result = --b;
[Link](result);
[Link](linebreak);
//-->
</script>
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...
Comparison Operators
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then –
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the
condition becomes true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values
are not equal, then the condition becomes true.
Ex: (A != B) is true.
3 > (Greater than)
Checks if the value of the left operand is greater than the value of
the right operand, if yes, then the condition becomes true.
Ex: (A > B) is not true.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
[Link]("(a == b) => ");
result = (a == b);
[Link](result);
[Link](linebreak);
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...
Logical Operators
JavaScript supports the following logical operators −
Assume variable A holds 10 and variable B holds 20, then −
[Link]. Operator & Description
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then
the Logical NOT operator will make it false.
Ex: ! (A && B) is false.
Example
Try the following code to learn how to implement Logical Operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...
Bitwise Operators
JavaScript supports the following bitwise operators −
Assume variable A holds 2 and variable B holds 3, then −
[Link]. Operator & Description
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit of its
integer arguments. Exclusive OR means that either operand one
is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different operators and then try...
Assignment Operators
JavaScript supports the following assignment operators −
[Link] Operator & Description
.
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=,
&=, |= and ^=.
Example
Try the following code to implement assignment operator in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...
1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
Example
Try the following code to understand how the Conditional Operator works in
JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which
can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a
number, string, or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the type of Operator.
Type String Returned by typeof
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example
The following code shows how to implement typeof operator.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
Output
Result => B is String
Result => A is Numeric
Points to Remember
✓ Arithmetic Operators
✓ Assignment Operators
✓ Comparison Operators
✓ String Operators
✓ Logical Operators
Duration: 6 hrs
Interpreter Compiler
• Recursive Algorithm:
• Randomized Algorithm:
• Sorting Algorithm:
• Searching Algorithm:
The searching algorithm is the algorithm that is used for searching the specific
key in particular sorted or unsorted data. Some common problems that can be
solved through the Searching Algorithm are Binary search or linear search is one
example of a Searching algorithm.
• Hashing Algorithm:
Structured English is the use of the English language with the syntax of
structured programming to communicate the design of a computer program to
non-technical users by breaking it down into logical steps using straightforward
English words. Structured English gives aims to get the benefits of both the
programming logic and natural language: program logic helps to attain precision,
whilst natural language helps with the familiarity of the spoken word.
Structure English is derived from structured programming language which gives
more understandable and precise description of process. It is based on
procedural logic that uses construction and imperative sentences designed to
perform operation for action.
• It is best used when sequences and loops in a program must be
considered and the problem needs sequences of actions with decisions.
• It does not have strict syntax rule. It expresses all logic in terms of
sequential decision structures and iterations.
For example, see the following sequence of actions −
if customer pays advance
then
Give 5% Discount
else
if purchase amount >=10,000
then
if the customer is a regular customer
then Give 5% Discount
Task:
A read function is a function which is used for inputs. It helps to receive the
value entered by a user and assign it to a variable.
Example:
Write an algorithm which receives a number entered by a user.
Answer:
Var A as Integer Start
read(A)
End
b. Write function
Write function is used for Inputs; it displays the content of a variable of displays
messages.
Syntax of write function:
Write( )
Example:
Write an algorithm which displays a value stored in a variable.
Answer:
Var B as Integer Start
B←5
Write(“The content of the variable is: ”)
Write(B)
If (condition)then
Block of
code
End if.
a. If …ElseIf….
If statement may be used inside another if statement, in such case we call it a
nested if.
Example:
Write an algorithm which receives student note and it displays the grade as
follows: Note form 16 and above: Grade A
Note14-16 : Grade B
Note12-14 : Grade C
Note below 12 : Grade D
Answer:
Start
Var Note as integer
Write(“Enter the Note”)
Example:
Write an algorithm which receives note and displays the student’s grade.
Answer:
Var Note as integer
Start
Write(“Use number to chose the range of your note”)
Write(“enter 1 for note ranging from 16 and above”)
Write(“enter 2 for note ranging from 14 to16”)
Write(“enter 3 for note ranging from 12 to14”)
Write(“enter 4 for note less than 12”)
Write(“enter your choice now using number:”)
Read(Note)
Switch(Note)
Case1
Write(“You have grade A”)
Case2
Write(“You have grade B”)
Case3
Write(“You have grade C”)
Case4
Write(“You have grade D”)
Default
Write(“Your choice is not listed, try again”)
End switch
End
What is a loop?
A loop is a sequence of instructions that is continually repeated until a certain
condition is reached.
A loop helps to repeat instruction or block of instructions. It assists in the
Syntax
Variable=<start value>
Do while <variable><comparison operator><end value>
Instruction or block of instructions
Variable=variable+1
Loop
Example:
Write an algorithm which use do while loop and displays numbers from 1 to 10
Answer:
Var A as integer Start
A=1
while A<=10
Write(A)
A=A+1
Loop
End
Do
Write(A)
A=A+1
while A>10
End
c. For loop
The for loop is an iterative loop, it specifies some elements about the loop
in one single line.
a. Setting a loop counter to an initial value.
b. End which determines whether its value has reached the number
of repetitions desired.
The value of the loop counter will be increased each time (iteration), and
segment within the loop will be executed.
Syntax:
for(<initialize counter>to <end of repetitions desired>) do
//bloc of instructions
End for
Example:
Write an algorithm which ask a user to enter a number and it displays the 10
next numbers.
Solution:
Loops in Loops
Loops in loops refer to what we call nested loops. These are loops that are such
that when one increment by one the other continues inside the first.
start
Var I, J As Integer
For I = 1 To 9 do
For J = 1 To I do
Write(J)
End for
End for
End
Tasks:
1: Read and answer the following questions:
i. What is flowchart
ii. Talk about advantages of flowchart
iii. Describe elements of flowchart
iv. Tools used to draw flowchart
v. Discuss flowchart best practices
● Designing a Flowchart
1. Introduction to Flowchart
Flowchart is diagrammatic /Graphical representation of sequence of steps to
solve a problem.
2. Advantages of flowchart:
✓ Flowchart is an excellent way of communicating the logic of a program.
✓ Easy and efficient to analyze problem using flowchart.
✓ During program development cycle, the flowchart plays the role of a
blueprint, which makes program development process easier.
✓ After successful development of a program, it needs continuous timely
maintenance during the course of its operation. The flowchart makes
program or system maintenance easier.
✓ It is easy to convert the flowchart into any programming language code.
3. NESTED IF statement
A NESTED IF is an IF statement that is the target of another if statement. Nested
if statements means an IF statement inside another IF statement.
Syntax
Start
If (condition)
If (condition) then
Instructions
…
Else
Instructions
End if
Else [optional]
Instructions
End if
End
Task:
You can create many different types of diagrams with [Link] and our online
diagram editor. To learn how to use the editor, let’s start with a basic flowchart
There are a number of different ways to add shapes to the drawing canvas in [Link].
Add the first step - Use one of the following methods to add a rectangle to the drawing
canvas. Rectangles represent the steps in your process.
• Click on a rectangle in the General shape library to add it the drawing canvas.
• Double-click on an empty area on the drawing canvas and select a rectangle
shape.
• Drag a rectangle from the General shape library to a specific position on the
drawing canvas.
• Drag a shape from the shape library and hover over an existing shape until you
can see the four direction arrows. Move over one of these direction arrows, and
drop the shape you have dragged. It will be added to the drawing canvas and
connected in that direction.
To select a shape, click on it. To select multiple shapes, hold down Shift or Cmd and
click on them.
Move - Select and drag a shape that is on the drawing canvas to another position.
Resize - Select a shape. Drag any of the round ‘grab’ handles to make the shape smaller
or larger. Hold down Control when you resize shapes to keep them centred.
See how to resize groups of shapes
Rotate - Select a shape. Drag the rotate grab handle (the round arrow) at the top right
corner of the shape to rotate the shape around its center point.
Connectors are lines that connect your shapes together and may or may not have
arrows at one or both ends.
Once you have finished adding all the shapes, connectors and labels, you can style your
flow chart.
1. Select a shape, or hold Shift down and click on multiple shapes and connectors to
select many.
You can share your diagram in a number of different ways via the File > Export as menu.
The most common export formats are as images or as a URL.
• Export as a PNG, JPEG or SVG to convert your diagram to an image that you can
paste into a website or email.
• Export as a URL to encode your entire diagram in a URL. When you share this
(very long) URL, the person viewing the diagram will see a copy - they don’t open
or edit your original diagram.
100|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
[Link] and share your flow chart
101|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Learning outcome 1 end assessment
Written assessment
Section 1: Read the Read the following statement related to data structure and
algorithm fundamentals, and choose the letter corresponding to the correct answer
1. Convert the binary number 1101 to its decimal equivalent.
a) 11
b) 12
c) 13
d) 14
2. Convert the decimal number 29 to its binary equivalent.
a) 11101
b) 10101
c) 11011
d) 10011
3. What is the hexadecimal equivalent of the binary number 10110110?
a) B6
b) 76
c) A6
d) C6
4. Convert the octal number 345 to its decimal equivalent.
a) 229
b) 229
c) 221
d) 231
5. What is the result of converting the hexadecimal number 2A to binary?
a) 101010
b) 110010
c) 100101
d) 111000
6. Which logic gate has an output of 1 only when both of its inputs are 1?
a) OR
b) AND
c) NOT
d) XOR
7. The output of an OR gate is 1 if:
a) Both inputs are 0
b) At least one input is 1
c) Both inputs are 1
d) Both inputs are different
8. If you want to build a circuit that outputs 1 when either input A is 1 or both
inputs B and C are 1, which combination of gates would you use?
a) OR and NOT
b) AND and OR
c) AND and NAND
d) XOR and NOR
102|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
9. Which of the following is a universal gate?
a) AND
b) OR
c) XOR
d) NAND
10. What is the decimal equivalent of the hexadecimal number 7F?
a) 127
b) 126
c) 124
d) 121
11. Which logic gate can be used to invert a binary input?
a) AND
b) OR
c) NOT
d) XOR
Section 2: Read the following statement related to data structure and algorithm
fundamentals, and answer by True if the statement is correct and False if the statement
is wrong
1. In JavaScript, the keyword var is used to declare a variable.
2. JavaScript variables are case-sensitive, meaning myVar and myvar are
considered the same variable.
3. A JavaScript variable name cannot start with a number.
4. In JavaScript, a variable declared with const can be reassigned later in the code.
5. JavaScript supports both let and const for block-level variable declarations.
6. The + operator in JavaScript can be used for both addition and concatenation.
7. The === operator checks for equality without type coercion in JavaScript.
8. The assignment operator in JavaScript is represented by ==.
9. In JavaScript, the && operator returns true only if both operands are true.
10. JavaScript has a ternary operator represented by?: that can be used for
conditional expressions.
Practical assessment
END
103|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
References
Books
Karumanchi, N. (2011 (2nd Edition)). Data Structures and Algorithms Made Easy: Data
Structures and Algorithmic Puzzles. Hyderabad, India: CareerMonk Publications.
Robert Sedgewick, K. W. (2011 (4th Edition)). Algorithms. Boston, MA, USA: Addison-
Wesley.
Skiena, S. S. (2020 (3rd Edition)). The Algorithm Design Manual. New York, USA: Springer.
Thomas H. Cormen, C. E. (2009 (3rd Edition)). Introduction to Algorithms. Cambridge, MA,
USA: The MIT Press.
Web links
drawio. (2023). doc/getting-started-basic-flow-chart. Retrieved from drawio:
[Link]
geeksforgeeks. (2023). javascript-data-types. Retrieved from geeksforgeeks:
[Link]
tutorialspoint. (2024).
programming_methodologies/programming_methodologies_flowchart_elements.ht
m. Retrieved from tutorialspoint:
[Link]
dologies_flowchart_elements.htm
Sw3schools. (n.d.). /js/js_datatypes.asp. Retrieved from w3schools:
[Link]
104|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Learning Outcome 2: Apply Data Structure
105|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Indicative contents
2.1 Identification of data structure concepts
2.2 Application of linear data structures and their operations
2.3 Application of non-linear data structure and their operations
106|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Duration: 45 hrs.
Learning outcome 2 objectives:
By the end of the learning outcome, the trainees will be able to:
1. Describe clearly Data structure concepts based on intended use.
2. Apply properly Linear Data Structures based on their operational complexity.
3. Apply properly Non-Linear Data Structures based on their operational
complexity.
Resources
107|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Indicative content 2.1: Identification of Data Structure Concepts
Duration: 25 hrs.
Tasks:
1: Answer the following questions:
[Link] deeply what is data structure?
[Link] Characteristics of Data structures?
iii. Discuss about types of Data structures?
[Link] classifications of data structures?
[Link] list representation
[Link] what structure is in programming.
2: Present your findings
3: Ask question
4: Read the Key readings [Link] in your manual
108|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
The data structures have the following importance for programming:
• Data structures study how data are stored in a computer so that operations can
be implemented efficiently
• Data structures are especially important when there is a large amount of
information to deal with.
• Data structures are conceptual and concrete ways to organize data for efficient
storage and manipulation
✓ Linear or Non-Linear
This characteristic arranges the data in sequential order, such as arrays, graphs etc.
✓ Time Complexity
The time factor should be very punctual. The running time or the execution time of
a program should be limited. The running time should be as less as possible. The
less the running time, the more accurate the device is.
✓ Correctness
Each data must definitely have an interface. Interface depicts the set of data
structures. Data Structure should be implemented accurately in the interface.
✓ Space Complexity
The Space in the device should be managed carefully. The memory usage should
be used properly. The space should be less occupied, which indicates the proper
function of the device.
109|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
• Non-primitive data structure
Check out the graph below to better understand how data structure types are categorized.
110|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Check out the graph below to better understand how data structure types are
categorized.
111|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
The data elements in the non-linear data structures are connected to one or more
elements.
There are two types of non-linear data structures. They are:
• Tree Data Structure
• Graph Data Structure
• Table Data Structure
112|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
3. Queue Data Structure
Unlike stack, the queue data structure works in the FIFO principle where first
element stored in the queue will be removed first.
It works just like a queue of people in the ticket counter where first person on the
queue will get the ticket first.
113|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Popular Non-linear data structures are:
1. Graph Data Structure
In graph data structure, each node is called vertex and each vertex is connected to
other vertices through edges.
114|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
3. Hash table data structure
A hash table or hash map stores key-value pairs in an array. The key is a unique
identifier to access or retrieve the value, which is the associated data or
information.
The hash function takes a key as input and produces a unique numerical value
called a hash code that serves as an index for a particular data element. This
115|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
mapping process is deterministic, meaning the same key will always be hashed to
the same index, facilitating rapid lookup and retrieval of values.
We use hash tables to quickly map keys to specific locations in the array. The goal
of the hash function is to distribute keys appropriately across the array indices,
minimizing collisions (situations where multiple keys map to the same index).
Hash tables are common in scenarios where efficient storage and retrieval of key-
value pairs are required — for example, caching systems. Additionally, we employ
hash tables in data processing tasks such as indexing and deduplication.
116|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
2.2 List operations
List operations refer to the various actions that can be performed on lists, whether
they are implemented as arrays, linked lists, or other data structures. Here we have
common list operations and their typical implementations:
• Insertion operation:
Refers to add a new element to the list.
✓ Types Insertion operation in list
At the End: Adding an element to the end of the list (often referred to as
appending).
At a Specific Position: Adding an element at a specific index or location in
the list.
✓ Implementation in list
Arrays: Inserting at the end is usually straightforward, but inserting at a
specific position requires shifting elements.
Linked Lists: Inserting is generally efficient as it involves updating pointers.
For singly linked lists, the insertion might require traversal to find the
correct position.
• Deletion operation:
Refers to removing an element from the list.
✓ Types in list
By Value: Removing the first occurrence of a specific value.
By Index: Removing the element at a specific index or position.
✓ Implementation in list
Arrays: Removing an element requires shifting elements to fill the gap.
Linked Lists: Deleting involves updating pointers. In a doubly linked list,
deletion is efficient as both previous and next pointers are available.
• Traversal Operation
Refers to visit each element of the list to perform some operation.
✓ Implementation in list
Arrays: Simple iteration through indices.
Linked Lists: Requires starting from the head and following pointers to visit
each node.
Sorting: Arranging the elements of the list in a specific order (e.g., ascending
or descending).
Update: refers to modify the value of an element at a specific index or
position.
7. STRUCTURES
Structures (also called structs) are a way to group several related variables into
one place. Each variable in the structure is known as a member of the structure.
117|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Unlike an array, a structure can contain many different data types (int, float, char,
etc.).
7.1Characteristics of Structures in Programming
• Composite Data Type: Structures allow you to create complex data types by
combining simpler data types, such as integers, floats, and strings.
• Member Variables: Each structure can contain multiple member variables. These
can be of different types and are accessed using a dot notation.
• Encapsulation: Structures encapsulate related data, making it easier to manage
and pass around as a single unit. This is especially useful for grouping related data
fields together.
• Data Alignment: In some languages, structures may have specific alignment
requirements or padding to ensure efficient access. This can affect the size of the
structure.
• User-defined: Structures are user-defined types, meaning that programmers can
create them according to their needs.
Tasks:
1: Answer the following questions:
i. Explain searching techniques
ii. Describe sorting techniques
iii. Describe two types of algorithm complexity
2: Present your findings
3: Ask clarifying question if any
4: Read the Key readings [Link]
118|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
memory. These sets of items are in different forms, such as an array, linked list,
graph, or tree.
Another way to define searching in the data structures is by locating the desired
element of specific characteristics in a collection of items. Different Searching
Methods Searching in the data structure can be done by applying searching
algorithms to check for or extract an element from any form of stored data
structure.
These algorithms are classified according to the type of search operation they
perform, such as:
● Sequential search
The list or array of elements is traversed sequentially while checking every
component of the set. For example – Linear Search.
● Interval Search
The interval search includes algorithms that are explicitly designed for searching
in sorted data structures. In terms of efficiency, these algorithms are far better
than linear search algorithms. Example- Logarithmic Search, Binary search.
2. Classification of Sorting Algorithms
Sorting is an algorithm that arranges the elements of a given list in a particular
order [ascending or descending].
● Sorting algorithms are categorized on the following basis
✓ By number of comparisons: Comparison-based sorting algorithms check the
elements of the list by key comparison operation and need at least O(n log n)
comparisons for most inputs. In this method, algorithms are classified based on the
number of comparisons. For comparison-based sorting algorithms, best case
behavior is O(n log n) and worst case behavior is O(n2). For example – Quick Sort,
Bubble Sort, Insertion Sort etc.
✓ By Memory Usage: Some sorting algorithms are “in place” and they need
O(1) or O(log n) memory to create auxiliary locations for sorting the data
temporarily.
119|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
✓By Recursion: Sorting algorithms are either recursive (for example – quick
sort) or non-recursive (for example – selection sort, and insertion sort), and
there are some algorithms which use both (for example – merge sort).
120|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Practical Activity 2.1.2: Selecting appropriate data structure algorithm
Task:
121|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Key readings 2.1.2:Selecting appropriate data structure
1. Bubble sort
Bubble Sort is a simple-minded algorithm based on the idea that we look at the
list, and wherever we find two consecutive elements out of order, we swap them.
This is done as follows: Repeatedly traverse the unsorted part of the array by
comparing consecutive elements, and interchange them when they are out of
order
See below demonstration:
2. Insertion sort
The Insertion Sort is a comparison-based algorithm that builds a final sorted array
one element at a time. It iterates through an input array and removes one element
per iteration, finds the place if the element belongs in the array, and then places
it there. The illustration is given here below:
122|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
The
Insertion Sort traverses the array and inserts each element into the sorted part of
the list where it belongs. It involves pushing down the larger elements in the sorted
part.
3. Selection sort
The Selection Sort is a simplicity sorting algorithm. Here are basic steps of
selection sort algorithm:
The idea of Selection Sort is that we repeatedly find the smallest element in the
unsorted part of the array and swap it with the first element in the unsorted part
of the array.
4. Merge Sort
Merge sort is a sorting algorithm that follows the divide-and-conquer approach.
It works by recursively dividing the input array into smaller sub arrays and sorting
those sub arrays then merging them back together to obtain the sorted array.
Points to Remember
• Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It
works by recursively dividing the input array into smaller sub arrays and sorting
those sub arrays then merging them back together to obtain the sorted array.
123|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
• Quicksort is a sorting algorithm based on the Divide and Conquer algorithm that
picks an element as a pivot and partitions the given array around the picked pivot
by placing the pivot in its correct position in the sorted array.
• Heap Sort is a comparison-based sorting algorithm that uses a binary heap data
structure.
• Radix Sort is a non-comparison-based sorting algorithm that sorts numbers by
processing individual digits.
• Counting Sort is a non-comparison-based sorting algorithm suitable for sorting
integers within a specific range.
• Bucket Sort is a non-comparison-based sorting algorithm that distributes elements
into several buckets and then sorts each bucket individually (using a different
sorting algorithm, like Insertion Sort).
• Shell sort is a generalized version of the insertion sort algorithm. It first sorts
elements that are far apart from each other and successively reduces the interval
between the elements to be sorted.
124|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Indicative content 2.2: Application of Linear Data Structures and their
Operations
Duration: 8 hrs
Tasks:
1: Answer the following questions:
i. Define a linear data structure.
ii. Identify Data Structure Operations
iii. Explain application of linear data structure and examples.
2: Present your findings
3: Ask question
4: Read the Key readings 2.2.1 in your manual
125|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
I. ARRAYS
• An array is a collection of elements identified by index or key, where each
element is of the same data type and stored at contiguous memory locations
• Arrays dimensions:
A dimension of array is a direction in which you can vary the specification of an
array's elements. An array can be of one or many dimensions.
a) One-dimensional array.
Example: a [3] It is an array called a with 3 elements. The elements of the array
are logically represented by the name of the array with in brackets its index or
positions. For the one dimensional array a with 3 elements, elements are written
like a[0], a[1] and a[2]. The indexes start always by 0. Graphically, it is
b) Two-dimensional array.
A Two-dimensional Array is a collection of a fixed number of elements
(components) of the same type arranged in two dimensions. The two-dimensional
array is also called a matrix or a table. The intersection of a column and a row is
called a cell. The numbering of rows and columns starts by 0 Example: The array
a[3][4] is an array of 3 rows and 4 columns. In matrix representation, it looks like
the following:
a[i][j] means that it is an element located at the intersection of row i and column
j.
Each element is identified by its row and column.
126|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Types of linked lists
Linked list is classified into three types as shown below:
a) Single linked lists
b) Double linked lists
c) Circular linked list
We can use the following steps to insert a new node after a node in the double
linked list
Step 1: Create a new Node with given value.
Step 2: Check whether list is Empty (head == NULL)
127|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Step 3: If it is Empty then, assign NULL to newNode => previous&newNode => next
and New Node to head.
Step 4: If it is not Empty then, define two node pointers temp1&temp2 and
initialize temp1 With head.
Step 5: Keep moving the temp1 to its next node until it reaches to the node after
which we want to insert the newNode (until temp1 => data is equal to location,
here location is the Node value after which we want to insert the newNode).
Step 6: Every time check whether temp1 is reached to the last node. If it is
reached to the last node then display ‘Given node is not found in the list!!!
Insertion not possible!!!’ and Terminate the function. Otherwise move the temp1
to next node.
Step 7: Assign temp1 => next to temp2, newNode to temp1=> next, temp1 to
newNode => Previous, temp2 to newNode => next and newNode to temp2 =>
previous.
128|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Step 11: If temp is the last node then set temp of previous of next to NULL (temp
=>
Previous => next = NULL) and delete temp (free (temp)).
Step 12: If temp is not the first node and not the last node, then set temp of
previous of next to temp of next (temp => previous => next = temp => next), temp
of next of previous to temp of previous (temp => next => previous = temp =>
previous) and delete temp (Free (temp)).
III. QUEUE
A queue is a linear list in which data can only be inserted at one end, called the
REAR, and deleted from the other end, called the FRONT. These restrictions ensure
that the data is processed through the queue in the order in which it is received.
In other words, a queue is a structure in which whatever goes fist comes out first
(first in, first out (FIFO) structure).
129|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Queue representation
Types of queues
There exist two types of queues:
a. Linear queue
b. Circular queue
a. Linear Queue
Queue data structure is a linear data structure in which the operations are
performed based on FIFO principle. Queue Operations using Array before we
implement actual operations, first follow the below steps to create an empty
queue,
Step 1: Include all the header files which are used in the program and define a
constant ‘SIZE’ with specific value.
Step 2: Declare all the user defined functions which are used in queue
implementation.
Step 3: Create a one dimensional array with above defined SIZE (int queue[SIZE])
Step 4: Define two integer variables ‘front’ and 'rear' and initialize both with ‘-1’.
(int front = 1, rear = -1)
Step 5: Then implement main method by displaying menu of operations list and
make suitable function calls to perform operation selected by the user on queue.
130|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Step 2: If it is EMPTY, then display “Queue is EMPTY!!! Deletion is not possible!!!”
and terminate the function.
Step 3: If it is NOT EMPTY, then increment the front value by one (front ++). Then
display queue[front] as deleted element. Then check whether both front and rear
are equal (front == rear), if it TRUE, then set both front and rear to ‘-1’ (front = rear
= -1).
Step 1: Include all the header files which are used in the program and define a
constant ‘SIZE’ with specific value.
Step 2: Declare all user defined functions used in circular queue implementation.
Step 3: Create a one dimensional array with above defined SIZE (int cQueue[SIZE])
Step 4: Define two integer variables ‘front’ and ‘rear’ and initialize both with ‘-1’.
(int
front = -1, rear = -1)
Step 5: Implement main method by displaying menu of operations list and make
suitable
131|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
function calls to perform operation selected by the user on circular queue.
Step 1: Check whether queue is FULL. ((rear == SIZE-1 && front == 0) || (front ==
rear+1))
Step 2: If it is FULL, then display “Queue is FULL!!! Insertion is not possible!!!” and
terminate the function.
Step 3: If it is NOT FULL, then check rear == SIZE - 1 && front != 0 if it is TRUE, then
set rear = -1.
Step 4: Increment rear value by one (rear++), set queue[rear] = value and check
'front
== -1' if it is TRUE, then set front = 0.
deQueue() - Deleting a value from the Circular Queue
Queue operations
132|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
There are two main operations related to queues.
• Enqueue: the enqueue operation insert an item at the rear of the queue
• Dequeue: the dequeue operation deletes the item at the front of the
queue.
Task:
133|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
at the top, we must first remove all objects above it. The following charts illustrates
cases of stack.
Stack presentation
A Stack is a Last in First out (LIFO) dynamic table or data structure. It has the following
characteristics:
• List of the same kind of elements;
• Addition and deletion of elements occur only at one end, called the top of the
stack;
• Computers use stacks to implement method calls;
• Stacks are also used to convert recursive algorithms into non recursive algorithm.
134|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
• Stack underflow exception: it occurs if you try to remove an item from an empty
queue or stack.
Points to Remember
● Linear Data Structures are simpler and involve direct, sequential relationships (like
Arrays, Linked Lists, Stacks, and Queues).
● Arrays: An array is a collection of elements identified by index or key, where each
element is of the same data type and stored at contiguous memory locations.
● Linked List: A linked list is a linear data structure where each element (node)
contains a data part and a reference (or link) to the next node in the sequence.
● Stack: A stack is a linear data structure that follows the Last In, First Out (LIFO)
principle.
● Queue: A queue is a linear data structure that follows the First In, First Out (FIFO)
principle.
● A stack underflow occurs when you try to pop an item from an empty stack.
Essentially, it happens when there are no elements to remove.
● A stack overflow occurs when you try to push an item onto a stack that is already
full. In other words, it happens when there is no more space available to add new
elements.
A grocery store implements a system where the last product scanned at checkout can be
removed if the customer changes their mind. Which linear data structure would be best
for this functionality, and how would it operate?
135|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Indicative content 2.3: Application of Non-Linear Data Structures and their
Operations
Duration: 7 hrs.
136|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
1. Tree
In linear data structure, data is organized in sequential order and in non-linear
data structure; data is organized in random order. Tree is a very popular data
structure used in wide range of applications. A tree data structure can be defined
as follows. Tree data structure is a collection of data (Node) which is organized in
hierarchical structure, and this is a recursive definition.
In a tree data structure, if we have N number of nodes then we can have a
maximum of N-1 number of links.
Tree Terminology
In a tree data structure, we use the following terminology:
a) Root
In a tree data structure, the first node is called as Root Node. Every tree must have
root node.
b) Edge
In a tree data structure, the connecting link between any two nodes is called an
Edge. In a tree with 'N' number of nodes there will be a maximum of 'N-1' number
of edges.
c) Parent
In a tree data structure, the node which is predecessor of any node is called a
PARENT NODE. In simple words, the node which has branch from it to any other
node is called as parent node.
137|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
d) Child
In a tree data structure, the node which is descendant of any node is called a CHILD
Node. In a tree, any parent node can have any number of child nodes. In a tree, all
the nodes except root are child nodes.
e) Siblings
In a tree data structure, nodes which belong to same Parent are called SIBLINGS.
f) Leaf
In a tree data structure, the node which does not have a child is called a LEAF
Node. In a tree data structure, the leaf nodes are also called a External Nodes or
Terminal node.
138|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
• Applications of Graph
✓ Robot planning: Vertices represent states the robot can be in and the edges
the possible transitions between the states. Such graph plans are used, for
example, in planning paths for autonomous vehicles.
✓ In GPS. The problems like finding the closest route, closest petrol pumps, etc
are all soled using graph problems.
✓ For optimizing the cost of connecting all locations of a network. For example,
minimizing wire length in a wired network to make sure all devices are
connected is a standard Graph problem called Minimum Spanning Tree.
139|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
✓ Can be used to represent the topology of computer networks, such as the
connections between routers and switches.
✓ Dependencies in a software project (or any other type of project) can be seen
as graphs and generating a sequence to solve all tasks before dependents is
a standard graph topological sorting algorithm.
• Difference Between Graph and Tree
Graphs and trees are two fundamental data structures used in computer science
to represent relationships between objects. While they share some similarities,
they also have distinct differences that make them suitable for different
applications.
140|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Practical Activity 2.3.1: Selecting an appropriate non-linear data
structure to solve problem
Task:
2. Infinite Graph
A graph is said to be infinite if it has an infinite number of vertices as well as an
infinite number of edges.
141|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
3. Trivial Graph
A graph is said to be trivial if a finite graph contains only
one vertex and no edge. A trivial graph is a graph with
only one vertex and no edges. It is also known as a
singleton graph or a single vertex graph.
4. Simple Graph
A simple graph is a graph that does not contain more than one edge between the
pair of vertices.
5. Multi Graph
Any graph that contains some parallel edges but doesn’t contain any self-loop is
called a multigraph. For example a Road Map.
Parallel Edges: If two vertices are connected with more than one edge then such
edges are called parallel edges that are many routes but one destination.
Loop: An edge of a graph that starts from a vertex and ends at the same vertex is
called a loop or a self-loop.
6. Null Graph
A graph of order n and size zero is a graph where there are only isolated vertices
with no edges connecting any pair of vertices. A null graph is a graph with no edges.
In other words, it is a graph with only vertices and no connections between them.
A null graph can also be referred to as an edgeless graph, an isolated graph, or a
discrete graph
142|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Points to Remember
You are designing a market distribution network where each main warehouse supplies multiple
regional warehouses, and each regional warehouse, in turn, supplies several local stores.
However, there are also direct routes between some local stores for emergency supplies. How
would you model this system using a combination of graph and tree structures?
143|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Learning outcome 2 end assessment
Written assessment
I. Read the Read the following statement related to data structure and algorithm
fundamentals, and choose the letter corresponding to the correct answer
1. Which of the following is an example of a non-linear data structure?
a) Linked List
b) Queue
c) Stack
d) Tree
2. Which sorting algorithm does NOT use recursion?
a) Quick Sort
b) Merge Sort
c) Insertion Sort
d) Heap Sort
3. Which of the following operations is common to both linear and binary search?
a) Sorting the data before searching
b) Comparing elements
c) Splitting the data into two halves
d) Reversing the data
4. What is the best sorting algorithm to use when stability is a requirement?
a) Quick Sort
b) Merge Sort
c) Heap Sort
d) Shell Sort
5. Which classification of sorting algorithms involves comparing elements to one
another?
a) By Recursion
b) By Memory Usage
c) By Number of Comparisons
d) By Stability
II. Read the following statement related to data structure and algorithm fundamentals,
and answer by True if the statement is correct and False if the statement is wrong
1. A binary search can be used on unsorted data
2. Merge Sort is both a stable and recursive sorting algorithm
3. Arrays and linked lists are examples of non-linear data structures.
4. The number of swaps is a classification criterion for sorting algorithms.
5. Time complexity measures the amount of memory an algorithm uses during
execution
144|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Practical assessment
Hasha Ltd is facing challenges in managing its warehouse data due to the use of hard copies
for record-keeping. As a solution, you have been tasked with creating an efficient data
management system that handles imports, exports, and transit processes for furniture.
Use the following data structures: Stack, Sorting, and Linked List to develop the system.
For each question below, write an algorithm that addresses the respective problem:
1. The company receives shipments daily, and the manager needs to process them in
the order they arrive. Sometimes the manager needs to undo the last action (removal of
incorrect shipments). Write an algorithm using a Stack to manage this process. The stack
should allow the manager to undo the last operation efficiently. Define the methods
needed to push, pop, and check the top of the stack.
2. The warehouse manager needs to sort furniture items by categories such as Tables,
Chairs, Beds, and Dressers to produce a daily report. Write an algorithm using a Sorting
Algorithm to organize these categories. Explain which sorting algorithm (e.g., Quick
Sort, Merge Sort, Bubble Sort, etc.) you would choose and why it is appropriate for this
situation.
3. The number of shipments in the warehouse can vary daily, so a flexible data structure
is needed. Write an algorithm using a Linked List to represent the furniture items in the
warehouse, allowing dynamic addition and removal of items. Explain how the linked list
supports these operations and how you would traverse the list to generate reports
END
145|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
References
BOOKS
Algorithms, L. J. (2016). Loiane Groner. Birmingham, UK: Packt Publishing.
Bae, S. (2017). Data Structures and Algorithms with JavaScrip. UK: Packt Publishing.
WEB LINKS
programiz. (2024). /dsa/data-structure-types. Retrieved from programiz:
[Link]
146|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Learning Outcome 3: Implement Algorithm Using JavaScript
147|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Indicative contents
148|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Duration: 55 hrs
Learning outcome 2 objectives:
By the end of the learning outcome, the trainees will be able to:
1. Describe correctly JavaScript running environment in line of its type
2. Prepare properly JavaScript running environment in accordance with computer
operating system
3. Write properly JavaScript Source code based on Algorithm
4. Run successfully JavaScript source code in accordance with expected result
5. Describe properly Key concepts of measuring time and space complexity based on
properties of developed program
6. Test successfully Time and space complexity based on data structure standards
Resources
● [Link] ● Internet
● Computer
● jsPerf
● WebStorm
● Visual Studio Code IDE built-in
profiling tool
● Frame graphs
● Blackfire
● YSlow
● Chrome/Microsoft/Firefox
DevTools
149|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Indicative content 3.1: Development of JavaScript Source Code
Duration: 20 hrs
Tasks:
1: Read the given task
To get started with JavaScript programming, especially for implementing data
structures like Linked Lists, Arrays, Queues, Stacks, Trees, Graphs, and Tables, you
need to set up a development environment. Go in computer LAB and prepare
environment to run JavaScript programs.
2: Follow the demonstration of trainer
3: Individually perform the task 3.1.1 referring to the demonstration
4: Ask for assistance where it is needed.
5: Read the key readings 3.1.1 in trainee’s Manual
Before writing any code, it’s important to set up the environment where you’ll run your
JavaScript programs. Here's how to prepare the environment:
✓ Choose an Editor or IDE: You can use text editors like Visual Studio Code,
Sublime Text, or an Integrated Development Environment (IDE) such as
WebStorm.
✓ Install [Link] (optional): If you want to run JavaScript outside the browser, you
can install [Link]. This allows you to execute JavaScript programs directly on
your system.
Download from [Link] official website.
After installation, you can run JavaScript files using the terminal with
node [Link].
150|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
✓ Browser Console: You can also run JavaScript directly in your web browser (e.g.,
Chrome, Firefox). Open the Developer Tools (F12) and use the Console to write
and execute JavaScript code.
Task:
151|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
This is basically the prerequisite in order to implement a linked list in JavaScript. In this
step, 2 classes namely one for the nodes and the other for the linked list need to be
created.
A constructor is a special function that creates and initializes an object instance of a
class. In JavaScript, a constructor gets called when an object is created using the new
keyword. The purpose of a constructor is to create a new object and set values for
any existing object properties.
1. The Node class represents a single node in the linked list. It has two properties
which are data and next. The data property is used to store the actual data of the
node, whereas the next property is a reference to the next node in the list. The Node
class consists of a constructor that initializes the data and next property when
creating a new Node.
class Node { constructor(data) { [Link] = data; [Link] = null;
}
}
2. The LinkedList class is a representation of the linked list itself. It has a head
property that refers to the first node in the list. The LinkedList class also has a
constructor that initializes the head property when creating a new LinkedList.
class LinkedList { constructor() { [Link] = null; [Link] = null; [Link]
= 0;
}
}
3. The LinkedList class also consists of a method that allows you to insert, delete,
and search for nodes in the list while simultaneously allowing other operations like
printing the list, counting the elements, reversing the list and so on.
✓ Printing the linked list
You can print the elements of a linked list by traversing through the list and printing
the data of each node.
printAll() {
let current = [Link];
while (current) {
[Link]([Link]);
current = [Link];
}
}
✓ Adding Node to the Linked List
152|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
There are multiple methods to add data to a linked list depending on where the new
node has to be inserted, and are as follows −
Adding node to the beginning of the linked list
To add node/ element at the start of a linked list, once a new node is created with the
data, simply set its next property to the current head of the list. Then you can update
the head of the list to the new node. This is also known as Insertion at the head of the
linked list and is the most basic type of addition of data. It is simply done by calling the
add function defined below.
add(data) {
const newNode = newNode(data);
if (![Link]) {
[Link] = newNode;
[Link] = newNode;
} else {
[Link] = newNode;
[Link] = newNode;
}
[Link]++;
return this;
}
Adding node to the end of the linked list
To add node/ element at the end of a linked list, we need to traverse the list and find
the last node. After which a new node with data is created and we set the next property
of the last node to the new node. This is also known as Insertion at the tail of the linked
list and is the second most basic type of addition of data. It is simply done by calling the
addToTail function defined below.
addToTail(data) {
let newNode = new Node(data);
if ([Link] === null) {
[Link] = newNode;
return;
}
let current = [Link];
while ([Link] !== null) {
current = [Link];
}
[Link] = newNode;
153|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
}
To add node/ element at a specific position in a linked list, you can traverse the list to
find the node at the position before the insertion point, create a new node with the
data, set the next property of the new node to the current node at the position, and set
the next property of the previous node to the new node.
addAtPosition(data, position) { let newNode = new Node(data); if (position === 1)
{ [Link] = [Link]; [Link] = newNode; return; }
let current = [Link];
let i = 1; while (i < position – 1 && current) {
current = [Link];
i++;
}
if (current) {
[Link] = [Link]; [Link] = newNode;
}}
Example (Adding Nodes to the Linked List)
In the below example, we implement adding nodes at beginning, at end and at a
specific position.
// this function is used to iterate over the entire linkedlist and print it
printAll() { let current = [Link]; while (current) {
[Link]([Link]); current = [Link];
}
} } const list = new LinkedList(); // add elements to the linkedlist [Link]("node1");
[Link]("node2"); [Link]("node3"); [Link]("node4"); [Link]("Initial List:");
[Link](); [Link]("List after adding nodex at position 2");
[Link]("nodex",2); [Link](); [Link]("List after adding nodey to
tail"); [Link]("nodey"); [Link]();
Output
Initial List: node1 node2 node3 node4
List after adding nodex at position 2 node1 nodex node2 node3 node4
List after adding nodey to tail node1 nodex
node2 node3 node4 nodey
154|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Removal of data too, can be done via several methods depending upon the
requirement.
To remove a specific node from a linked list, we need to traverse the list and find the
node before the one you want to remove, update its next property to skip over the
node you want to remove, and update the reference to the next node. This removes
the node based upon the value.
remove(data) {
if (![Link]) { return null;
} if ([Link] === data) { [Link] = [Link]; [Link]--;
return this;
}
let current = [Link]; while ([Link]) { if ([Link] === data) {
[Link] = [Link]; [Link]--; return this;
}
current = [Link];
} return null;
}
Removing a node at a Specific Position
To remove a node at a specific position in a linked list, we need to traverse the list and
find the node before the one you want to remove, update its next property to skip over
the node you want to remove, and update the reference to the next node. This is
basically removing the node based upon the index value of it.
removeAt(index) { if (index < 0 || index >= [Link]) return null; if (index === 0)
return [Link](); let current = [Link]; for (let i = 0; i < index - 1; i++) {
current = [Link];
}
[Link] = [Link]; [Link]--; return this; }
Example (Removing Nodes from the Lined List)
In the below example, we implement removing a specific node and a node at a specific
position.
class Node { constructor(data) { [Link] = data; [Link] = null;
} } class LinkedList { constructor() { [Link] = null; [Link] = null; [Link]
= 0;
}
// function to add data to linked list add(data) {
155|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
const newNode = new Node(data); if (![Link]) { [Link] = newNode;
[Link] = newNode;
} else { [Link] = newNode; [Link] = newNode;
} [Link]++; return this;
}
// function to remove data from linked list remove(data) { if (![Link]) {
return null;
}
if ([Link] === data) { [Link] = [Link]; [Link]--;
return this;
} let current = [Link]; while ([Link]) { if ([Link] ===
data) { [Link] = [Link]; [Link]--; return this;
}
current = [Link];
} return null;
}
// function to remove from a particular index removeAt(index) { if (index < 0
|| index >= [Link]) return null; if (index === 0) return [Link](); let
current = [Link]; for (let i = 0; i < index - 1; i++) { current = [Link];
}
[Link] = [Link]; [Link]--; return this;
}
// this function is used to iterate over the entire linkedlist and print it printAll() {
let current = [Link]; while (current) { [Link]([Link]); current
= [Link];
}
} } const list = new LinkedList(); // add elements to the linkedlist [Link]("node1");
[Link]("node2"); [Link]("node3"); [Link]("node4"); [Link]("Initial List:");
[Link]();
[Link]("List after removing node2"); [Link]("node2"); [Link]();
[Link]("List after removing node at index 2"); [Link](2); [Link]();
Output
Initial List: node1 node2 node3 node4
List after removing node2 node1 node3 node4
List after removing node at index 2 node1 node3
156|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Practical Activity 3.1.3: Implementing Array Data structure
Task:
Return value
It returns an array object.
When you pass the single numeric argument to the Array() constructor, it defines the array of
argument length containing the undefined values. The maximum length allowed for an array is
4,294,967,295.
You can add multiple comma separated elements inside square brackets to create an array
using the array literal −
const fruits = [ "apple", "orange", "mango" ];
157|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
Array Properties
Here is a list of the properties of the Array object along with their description −
1 constructor
Returns a reference to the array function that created the
object.
2 length
Reflects the number of elements in an array.
3 prototype
The prototype property allows you to add properties and
methods to an object.
Array Methods
Here is a list of the methods of the Array object along with their description −
Array Static methods
These methods are invoked using the Array class itself:
1 from()
Creates a shallow copy of the array.
2 isArray()
Returns boolean values based on the argument is an array.
3 Of()
Creates an array from multiple arguments.
158|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
<html>
<head>
<title> JavaScript - Array() constructor </title>
</head>
<body>
<p id = "demo"> </p>
<script>
const output = [Link]("demo"); let strs = new
Array("Hello", "World!", "Tutorials Point"); [Link] += "strs ==> " + strs
+ "<br>";
let cars = new Array(20); [Link] += "cars ==> " + cars + "<br>";
</script>
</body>
</html>
Output strs ==>
Hello,World!,Tutorials Point
cars ==> ,,,,,,,,,,,,,,,,,,,
Example: Creating Arrays Using Array Literal
In the example below, we have created different arrays. The arr1 array contains the
numbers, the arr2 array contains the strings, and the arr3 array contains the boolean
values.
<html>
<head>
<title> JavaScript - Array literals </title>
</head>
<body>
<p id = "output"> </p>
<script> const arr1 = [10, 40, 50, 60, 80, 90]; // Array of numbers
const arr2 = ["Hello", "Hi", "How", "are", "you?"]; // Array of strings
const arr3 = [true, false, true, true]; // Array of booleans
[Link]("output").innerHTML =
"arr1 ==> " + arr1 + "<br>" +
159|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
"arr2 ==> " + arr2 + "<br>" +
"arr3 ==> " + arr3;
</script>
</body>
</html>
Output
arr1 ==> 10,40,50,60,80,90
arr2 ==>
Hello,Hi,How,are,you?
arr3 ==> true,false,true,true
160|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
JavaScript Array length
The 'length' property of the array is used to find the length of the array.
let len = [Link];
Example
In the example below, the 'length' property returns 5, as array contains 5 elements.
<html>
<head>
<title> JavaScript - Array length </title>
</head>
<body>
<p id = "output"> </p>
<script> const nums = [1, 5, 6, 8, 90];
[Link]("output").innerHTML =
"Array length is : " + [Link];
</script>
</body>
</html>
Output
Array length is : 5
Adding a new element to the array
You can use the push() method to insert the element at the end of the array. Another
solution is that you can insert the array at the index equal to the array length.
[Link](ele)
OR
arr[[Link]] = ele;
In the above syntax, 'ele' is a new element to insert into the array. Here, if the array
length is N, the array contains elements from 0 to N – 1 index. So, we can insert the
new element at the Nth index.
Example
In the example below, we insert 6 to the array using the push() method. Also, we used
the 'length' property to insert the element at the end.
<html>
<body>
<p id = "output"> </p>
161|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
<script>
const output = [Link]("output");
const nums = [1, 2, 3, 4, 5];
[Link](6); // Inserting 6 at the end
[Link] += "Updated array is : " + nums + "<br>";
nums[[Link]] = 7; // Inserting 7
[Link] += "Updated array is : " + nums + "<br>"
</script>
</body>
</html>
Output
Updated array is : 1,2,3,4,5,6
Updated array is : 1,2,3,4,5,6,7
Updating Array Elements
To update any array element, you can access the array index and change its value.
arr[index] = ele;
In the above syntax, 'index' is an index where we need to update a value with the 'ele'
value.
Example
In the example below, we update the element at the first index in the array.
<html>
<body>
<p id = "output"> </p>
<script>
const nums = [1, 2, 3, 4, 5];
nums[0] = 100; // Updating first element
[Link]("output").innerHTML =
"Updated array is : " + nums;
</script>
</body>
</html>
162|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Output
Updated array is : 100,2,3,4,5
Traversing the Arrays
You can use the loop to traverse through each array element. However, some built-in
methods exist to traverse the array, which we will see in later chapters.
for (let p = 0;
p < [Link];
p++) {
// Access array using the nums[p]
}
Example
In the below code, the array contains 5 numbers. We used the for loop to traverse the
array and print each element.
However, while and do-while loops can also be used to traverse the array.
<html>
<body>
<p id = "demo"> </p>
<script>
const output = [Link]("demo");
const nums = [1, 2, 3, 4, 5];
for (let p = 0; p < [Link]; p++) {
[Link] += "nums[" + p + "] ==> " + nums[p] +
"<br>";
}
</script>
</body>
</html>
Output
nums[0] ==> 1 nums[1] ==> 2 nums[2] ==> 3 nums[3] ==> 4 nums[4] ==> 5
Situatuation
XYZ Police Station monitors traffic at four key intersections, and they have collected
vehicle count data for different hours of the day. The data is organized in the following
2D array, where rows represent intersections and columns represent hours:
Intersection/H H H H H
our 1 2 3 4
I1 5 6 5 4
0 0 5 5
163|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
I2 7 6 8 7
0 5 0 5
I3 3 4 3 5
0 0 5 0
I4 9 8 9 8
0 5 5 0
Based on this data, answer the following:
1. Calculate the total number of vehicles passing through each intersection over the
entire day.
2. Determine which hour had the highest total number of vehicles across all
intersections.
3. Identify which intersection has the highest average number of vehicles per hour.
4. Recommend a change in traffic light timing to improve traffic flow during peak
hours, based on your analysis. Explain your recommendation
164|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
const averageVehiclesPerIntersection = [Link](total =>
total / 4);
const highestAverageIntersectionIndex =
[Link]([Link](...averageVehiclesPerIntersec
tion));
// 4. Recommend a change in traffic light timing
// Assuming more green light should be allocated to intersections with high vehicle counts
during peak hours
const peakHourVehicles = totalVehiclesPerHour[peakHourIndex];
const vehiclesAtPeakHourPerIntersection = [Link](intersection =>
intersection[peakHourIndex]);
const highestPeakHourIntersectionIndex =
[Link]([Link](...vehiclesAtPeakHourPerIntersecti
on));
[Link]('Total vehicles per intersection:', totalVehiclesPerIntersection);
[Link]('Total vehicles per hour:', totalVehiclesPerHour);
[Link]('Peak hour index (H1=0, H2=1, H3=2, H4=3):', peakHourIndex);
[Link]('Intersection with highest average vehicles per hour:',
highestAverageIntersectionIndex);
[Link]('Recommended adjustment for traffic light timing at peak hour
intersection:', highestPeakHourIntersectionIndex);
// For readability, you might also want to map these indices back to meaningful
names
const intersectionNames = ['I1', 'I2', 'I3', 'I4'];
const hourNames = ['H1', 'H2', 'H3', 'H4'];
165|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
[Link]('Recommended adjustment for traffic light timing at intersection:',
intersectionNames[highestPeakHourIntersectionIndex]);
Explanation:
Data Initialization
This array represents the number of vehicles passing through four intersections (I1, I2,
I3, I4) at four different hours (H1, H2, H3, H4). Each inner array corresponds to one
intersection, with each number representing the vehicle count at a specific hour.
1. Calculate the Total Number of Vehicles Passing Through Each Intersection
[0, 1, 2, 3].map(hourIndex => ...) iterates over each hour index (H1 to H4).
[Link]((sum, intersection) => sum + intersection[hourIndex], 0) sums up
the vehicle counts for a specific hour across all intersections.
totalVehiclesPerHour will be an array where each element represents the total number
of vehicles for an hour.
166|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
• [Link](...totalVehiclesPerHour) finds the highest value in the
totalVehiclesPerHour array.
• [Link](...) gets the index of this maximum value, which
corresponds to the hour with the highest total vehicle count.
2. Identification of Intersection has the Highest Average Number of Vehicles per
Hour
167|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
value, which corresponds to the intersection with the highest vehicle
Task:
168|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
operations which are the addition of elements at the end of the queue and the
removal of elements from the front of the queue. Like Stack, Queue is also a linear
data structure.
To implement a queue data structure we need the following methods:
• enqueue : To add elements at the end of the queue.
• dequeue: To remove an element from the front of the queue.
• peek: To get the front element without removing it.
• isEmpty: To check whether an element is present in the queue or not.
• printQueue: To print the elements present in the queue.
Now, we will see the practical implementation of these queue operations, which are
as follows:
1) enqueue (): The queue operation which is used for adding elements to the queue.
Example:
enqueue(ele) {
if([Link] < [Link] ) { [Link][[Link]] = ele; [Link]
= [Link] + 1;
}
}
}
In the above code, we have added elements to the queue using the push function.
2) dequeue (): The queue operation which is used for removing or popping out the
existing values from the queue.
Example:
dequeue() { if([Link]() === false) { [Link] = [Link]-1;
return [Link]();
}
}
In the above code, firstly, we have checked if the queue is already empty or not. It is
because if the queue has no value, it will return "Underflow". Else, it will check and
return the element.
3) Length (): The queue operation is used to return the length of the queue.
Example:
length() {
return [Link];
}
169|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
The statement [Link] will help to fetch the length of the queue.
4) isEmpty (): The queue operation is used to check whether the queue is empty or
not. If the queue is found empty, it returns true. Otherwise, it returns false.
Example:
isEmpty() { return [Link] === 0;
}
In the above code, it will check if the value of the rear, i.e., the end, is equal to 0 or
not. If it is true, it will return true else false will be returned.
5) print (): The queue operation is used to print the elements of the queue from the
index value 0 to the rear position of the queue.
Example:
print() {
for(let i =0; i < [Link]; i++) { [Link]([Link][i]);
}
}
In the above code, using for loop and beginning from the 0 indexes to the queue's rear
position, it will print the value and put it in the data array.
6) clear (): The queue operation is used to clear or delete all the elements of the queue
and makes the value of the rear equal to 0.
Example:
clear() { [Link] =0;
[Link] = 0;
}
In the above code, using the clear () operation, the value in the data array becomes 0
and sets the rear value to 0.
Implementing the JavaScript Queue The complete code:
class Queue {
constructor(){
[Link] = [];
[Link] = 0;
[Link] = 20;
}
enqueue(ele) {
170|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
if([Link] < [Link] ) {
[Link][[Link]] = ele;
[Link] = [Link] + 1;
}
}
length() {
return [Link];
}
isEmpty() {
return [Link] === 0;
}
getFront() {
if([Link]() === false) {
return [Link][0];
}
}
getLast() {
if([Link]() === false) {
return [Link][ [Link] - 1 ] ;
}
}
dequeue() {
if([Link]() === false) {
[Link] = [Link]-1;
return [Link]();
}
}
print() {
for(let i =0; i < [Link]; i++) {
[Link]([Link][i]);
}
}
clear() {
[Link] = 0;
171|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
[Link] = 0;
}
}
Another example:
class Queue {
constructor() {
[Link] = {}
[Link] = 0
[Link] = 0
}
enqueue(item) {
[Link][[Link]] = item
[Link]++
return item + ' inserted'
}
dequeue() {
const item = [Link][[Link]] delete [Link][[Link]]
[Link]++
return item
}
peek() {
return [Link][[Link]]
}
get printQueue() { return [Link];
}
}
const queue = new Queue() [Link]([Link](7)) [Link]([Link](2))
[Link]([Link](6)) [Link]([Link](4))
[Link]([Link]()) [Link]([Link]()) let str = [Link];
[Link](str)
Task:
172|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
1: Read the task described below:
Create a stack class with methods for push (), pop(), and peek().
2: Follow the demonstration of trainer
3: Individually perform the task 3.1.5 referring to the demonstration
4: Ask for assistance where it is needed.
5: Read the key readings 3.1.5 in trainee’s Manual
Stack
In this article, we are going to discuss how to create the stack data structure in
JavaScript. It is a linear data structure where the push and popping of elements
follow the LIFO (last in first out and FILO (first in last out) sequence.
Though Arrays in JavaScript provide all the functionality of a Stack, let us
implement our own Stack class. Our class will have the following functions.
• push(element) − Function to push elements on top of the stack.
• pop() − Function that removes an element from the top and returns it.
• peek() − Returns the element on top of the stack.
• isFull() − Checks if we reached the element limit on the stack.
• isEmpty() − checks if the stack is empty.
• clear() − Remove all elements.
• display() − display all contents of the array
Let's start by defining a simple class with a constructor that takes the max size of
the stack and a helper function display() that'll help us when we implement the
other functions for this class. We have also defined 2 more functions, isFull and
isEmpty to check if the stack is full or empty.
The isFull function just checks if the length of the container is equal to or more
than maxSize and returns accordingly.
The isEmpty function checks if a size of the container is 0.
These will be helpful when we define other operations. The functions we define
from this point onwards will all go inside the Stack class.
Example 1
The following example demonstrates how to create the Stack Data Structure in
JavaScript. In this example, we are going to discuss the use of push(), and the pop()
173|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
methods. We create a stack and add the elements to it and display the stack
elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Creating Stack Data Structure</title>
</head>
<body>
<script type="text/javascript">
class Stack {
constructor() {
[Link] = [];
}
// add element to the stack
add(element) {
return [Link](element);
}
// remove element from the stack
remove() {
if ([Link] > 0) {
[Link]("<br>");
return "The Popped element is : " + [Link]();
}
}
// view the last element
peek() {
[Link]("<br>");
return (
"The Peek element of the stack is : " + [Link][[Link] - 1] );
}
// check if the stack is empty
174|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
isEmpty() {
[Link]("<br>");
return [Link] == 0;
}
// the size of the stack
size() {
[Link]("<br>");
return "The size of the stack is : " + [Link];
}
display() {
if ([Link] !== 0) {
return "The stack elements are : " + [Link] + "<br>";
} else {
[Link]("The Stack is Empty..! <br>");
}
}
// empty the stack
clear() {
[Link]("The stack is cleared..!" + "<br>");
[Link] = [];
}
}
let stack = new Stack();
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);
[Link]([Link]());
[Link]([Link]());
</script> </body>
175|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
</html>
Example 2
Another example to execute the operations of stack in JavaScript is given as
follows −
class Stack {
constructor(maxSize) {
if (isNaN(maxSize)) {
maxSize = 10;
}
[Link] = maxSize;
[Link] = [];
} display() {
[Link]([Link]);
}
push(element) {
[Link](element);
} } const obj = new Stack(10);
[Link](10);
[Link](44);
[Link](55);
[Link]();
Task:
176|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Key readings 3.1.6: Implementing Tree Data Structure
177|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
• Height (h) of the tree is the distance (edge count) between the farthest
leaf to the root.
A has a height of 3 o I has a height of 0
• Depth or level of a node is the distance between the root and the node
in question.
H has a depth of 2 o B has a depth of 1
Implementing a simple tree data structure
As we saw earlier, a tree node is just a data structure with a value and links to its
descendants.
class
Here’s an example of a tree node:
TreeNode {
constructo
r(value) {
[Link]
= value;
[Link]
ndants = [];
}
}
2
3
4
5
6
178|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
const bart = new TreeNode('Bart'); const lisa =
new TreeNode('Lisa'); const maggie = new
TreeNode('Maggie'); // associate root with is That’s all; we have a
descendants [Link](homer); tree data structure!
[Link](bart, lisa, maggie);
These properties are not always mutually exclusive. You can have more than
one:
• A perfect tree is always complete and full.
✓ Perfect binary trees have precisely 2k−12 -1 nodes, where k is the last level
of the tree (starting with 1).
• A complete tree is not always full.
✓ Like in our “complete” example, since it has a parent with only one child.
If we remove the rightmost gray node, then we would have a complete and
full tree but not perfect.
• A full tree is not always complete and perfect.
179|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Each node in a tree data structure must have the following properties:
key : The key of the node
value : The value of the node
parent : The parent of the node (null if there is none)
children: An array of pointers to the node's
children
Th e main operations of a tree data structure are:
inser : Inserts a node as a child of the given parent node
t : Removes a node and its children from the tree
remo Retrieves a given node preOrderTraversal:
ve Traverses the tree by recursively traversing each
find: node followed by its
childr
en
postOrderTraversal: Traverses the tree by
recursively traversing each node's children followed
by the node
Implementation
180|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
class TreeNode {
constructor(key, value = key, parent = null) {
[Link] = key;
[Link] = value;
[Link] = parent;
[Link] = [];
}
get isLeaf() {
return [Link] === 0;
}
get hasChildren() {
return ![Link];
}}
class Tree {
constructor(key, value = key) {
[Link] = new TreeNode(key, value);
}
*preOrderTraversal(node = [Link]) {
yield node;
if ([Link]) {
for (let child of [Link]) {
yield* [Link](child);
}
}
}
*postOrderTraversal(node = [Link]) {
if ([Link]) {
for (let child of [Link]) {
yield* [Link](child);
}
}
yield node;
}
insert(parentNodeKey, key, value = key) {
for (let node of [Link]()) {
181|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
• Define a find() method, that uses the preorder traversal ()
method to retrieve the given node in the tree.
Hash Table
Hash table is one of the most important data structures that uses a special
function known as a hash function that maps a given value with a key to access
the elements faster.
A Hash table is a data structure that stores some information, and the
information has basically two main components, i.e., key and value. The hash
table can be implemented with the help of an associative array. The efficiency of
mapping depends upon the efficiency of the hash function used for mapping.
For example, suppose the key value is John and the value is the phone number,
so when we pass the key value in the hash function shown as below:
Hash(key)= index;
When we pass the key in the hash function, then it gives the index.
Hash(john) = 3;
The above example adds the john at the index 3.
Drawback of Hash function
A Hash function assigns each value with a unique key. Sometimes hash table uses
an imperfect hash function that causes a collision because the hash function
generates the same key of two different values.
In Hashing technique, the hash table and hash function are used. Using the hash
function, we can calculate the address at which the value can be stored.
The main idea behind the hashing is to create the (key/value) pairs. If the key is
given, then the algorithm computes the index at which the value would be stored.
It can be written as:
Index = hash(key)
• Object: An object with the table where the data is stored. The array holds
all the keyvalue entries in the table. The size of the array should be set according
182|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
to the amount of data expected.
• Hash function (or mapping function): This function determines the
index of our key-value pair. It should be a one-way function and produce the a
different hash for each key.
To implement a hash table using JavaScript, we will do three things:
Create a hash table class, add a hash function, and implement a method
for adding key/value pairs to our table.
First, let’s create the HashTable class.
class HashTable {
constructor() {
[Link] = {};
[Link] = 0;
[Link] = 0;
}
}
The constructor contains an object in which we’re going to store the values, the
length of the values, and the entire size of the hash table: meaning how many
buckets the hash table contains.
We will be storing our data in these buckets.
Next, we have to implement a simple hashing function.
calculateHash(key) {
return [Link]().length % [Link];
}
This function takes the provided key and returns a hash that’s calculated using
an arithmetic modulus.
Finally, we need a method to insert key/value pairs. Take a look at the code and
see this in action:
add(key, value) {
const hash = [Link](key);
if() {
[Link][hash] = {};
}
if(![Link][hash].hasOwnProperty(key)) {
[Link]++;
}
[Link][hash][key] = value;
}
The first thing we do here is calculate a hash for our key. If the hash does not
already exist, we save it to our object store. The next check we perform is on the
183|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
hash. If it doesn’t have a key saved, we save the key and value and increment the
size of our hash table.
Searching in a hash table goes very fast. Unlike with an array where we have to
go through all of the elements until we reach the item we need, with a hash table
we simply get the index. I’ll add the complete code for our hash table
implementation below.
class
HashTab
le {
construc
tor() {
[Link]
es = {};
[Link]
th = 0;
[Link]
= 0;
}
calculateHash(key) {
return [Link]().length %
[Link]; } add(key, value) {
const hash =
[Link](key); If
() { [Link][hash] = {};
}
if (![Link][hash].hasOwnProperty(key)) {
[Link]++;
}
[Link][hash][key] = value;
}
sear
ch(k
ey) {
const hash = [Link](key); if
([Link](hash) &&
[Link][hash].hasOwnProperty(key)) {
return [Link][hash][key];
}
else {
184|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
return
null;
}
}
}
//create object of
type hash table const
ht = new HashTable();
//add data to the hash
table ht
[Link]("Canada",
"300");
[Link]("Germany",
"100"); [Link]("Italy",
"50");
//search
[Link]([Link]("Italy"));
Task:
This defines a new class called Graph. In JavaScript, a class is a blueprint for
185|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
creating objects
[Link] an Edge
186|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
neighbors of vertex2 (this is for an undirected graph; for a directed graph, you
would only add one of these).
3. Remove an Edge
This method simply logs the adjacency list to the console to show the current
structure of the graph.
187|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Work
Kiki ltd is road Construction Company located in Kigali city need to build road
network using a graph. Each city intersection is a vertex, and each road is an edge
between two intersections. As software development write JavaScript code using
Graph to:
a) Add intersections (vertices).
b) Add roads (edges).
c) Remove roads and intersections.
d) Display the network of roads
Task:
188|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
✓ Hash Table: This defines a new class for creating a hash table.
✓ Constructor (size = 53): The constructor initializes an array keymap with
a default size of 53 (this will hold the hashed keys and their values).
✓ New Array(size): This creates an empty array of length size to store the
key-value pairs
1. Hash Function
189|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
1. Set Method
✓ set(key, value): This method stores a key-value pair in the hash table.
✓ this._hash(key): First, it calculates the index for the key using the _hash
function.
✓ if (![Link][index]): Checks if the bucket at the calculated index is
empty. If so, it initializes an empty array (to handle collisions via
chaining).
✓ [Link][index].push([key, value]): Pushes the key-value pair into
the array at the hashed index.
2. Get Method
190|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
3. Retrieve Keys
191|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Practical Activity
Suppose that client asked you to use a hash table to store and retrieve user
information like name, age, and profession. Each user's name will be the key and store
additional user data like age and profession. By using JavaScript write code to:
a. Add user data (name, age, profession).
b. Retrieve data by name.
c. Display all stored users
Solution
// Hash table (object) to store user data
let users = {};
// Function to add user data
function addUser(name, age, profession) {
users[name] = {
age: age,
profession: profession
};
[Link](`User ${name} added successfully.`);
}
192|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
function displayAllUsers() {
[Link]("All stored users:");
for (let name in users) {
[Link](`Name: ${name}, Age: ${users[name].age}, Profession:
${users[name].profession}`);
}
}
// Example usage
addUser("Alice", 30, "Engineer");
addUser("Bob", 30, "Designer");
OUTPUT
193|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Practical Activity 3.1.9: Performing sort operations
Task:
194|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
// If the condition is true
// then swap them
var temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp
}
}
}
// Print the sorted array [Link](arr);
}
// This is our unsorted array var arr = [234, 43, 55, 63, 5, 6, 235, 547]; // Now pass this array to
the bblSort() function bblSort(arr);
Output: Sorted array
[5, 6, 43, 55, 63, 234, 235, 547]
Note: This implementation is not optimized. We will see the optimized solution next.
Optimized Solution
As we discussed the implementation of bubble sort earlier that is not optimized. Even if the
array is sorted, the code will run with O(n^2) complexity. Let’s see how to implement an
optimized bubble sort algorithm in javascript.
The syntax for Optimized solution BubbleSort(array){ for i -> 0 to arrayLength isSwapped
<- false for j -> 0 to (arrayLength - i - 1) if arr[j] > arr[j + 1] swap(arr[j],
arr[j + 1]) isSwapped -> true
}
Implementation function
bubbleSort(array) { const arrayLength = [Link]; let isSwapped;
for (let i = 0; i < arrayLength; i++) { isSwapped = false;
for (let j = 0; j < arrayLength - i - 1; j++) { if (array[j] > array[j + 1]) {
// Swap elements
[array[j], array[j + 1]] = [array[j + 1], array[j]]; isSwapped = true;
}
}
// If no two elements were swapped in the inner loop, array is sorted if (!isSwapped)
break;
} return array;
}
// Test the function const sortedArray = bubbleSort([45, 23, 3, 5346, 5, 356, 243, 35]);
[Link]("Sorted Array:"); [Link](sortedArray);
Output: Sorted Array
[3, 5, 23, 35, 45, 243, 356, 5346]
195|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
• Quick
What is Quick Sort Algorithm?
Quick sort is one of the sorting algorithms that works on the idea of divide and conquer. It takes
an element as a pivot and partitions the given array around that pivot by placing it in the
correct position in the sorted array. The pivot element can be selected in the following ways:
• Select the First element as a pivot
• Select the Last element as a pivot
• Select the Middle element as a pivot
• Select a Random element as a pivot
We will use the Last element as a pivot for this article.
Programmatic Approach for Quick Sort
• First, create a recursive function that takes array, low value and high value as input and calls
the partition function for recursive call for partitioned arrays.
• Define a partition function for last element as pivot and give the partition index of array.
• Partition function iterate the given array and compare elements to pivot. If smaller then
swap them to a sequential position else no swap is performed.
• At the end for iteration the pivot element is swapped to its correct position stored in i for
the exact place.
• Now return the latest position of the pivot element
Example: Here is the complete code for the Quick Sort algorithm using JavaScript.
function partition(arr, low, high) { let pivot = arr[high]; let i = low - 1; for (let j = low; j
<= high - 1; j++) {
// If current element is smaller than the pivot if (arr[j] < pivot) {
// Increment index of smaller element i++;
// Swap elements
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
// Swap pivot to its correct position
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]]; return i + 1; // Return the partition index
}
function quickSort(arr, low, high) { if (low >= high) return; let pi = partition(arr, low, high);
quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high);
}
let arr = [10, 80, 30, 90, 40]; [Link]("Original array: " + arr); quickSort(arr, 0, [Link] -
1); [Link]("Sorted array: " + arr);
Output
Original array: 10,80,30,90,40 Sorted array: 10,30,40,80,90
196|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Practical Activity 3.1.10: Performing search operations
Task:
197|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
// Example Usage
[Link]("Price of Laptop:", linearSearch(products, "Laptop")); // Output: 1200
[Link]("Price of Monitor:", linearSearch(products, "Monitor")); // Output: 300
[Link]("Price of Tablet:", linearSearch(products, "Tablet")); // Output: Product
not available
❖ const products:
This creates a constant array called products that stores objects.
Each object has two properties:
Name: The name of the product (a string).
Price: The price of the product (a number).
const products = [
{ name: "Laptop", price: 1200 },
{ name: "Mouse", price: 25 },
{ name: "Keyboard", price: 50 },
{ name: "Monitor", price: 300 },
{ name: "Headphones", price: 100 },
];
for (let i = 0; i < [Link]; i++) {
❖ for loop:
• Iterates through the products array.
• let i = 0: Starts the loop with i as 0 (first index).
• i < [Link]: Ensures the loop runs until the last product in the array.
• i++: Increases the index i by 1 after each iteration
Purpose: To search for a specific product in the array
❖ if statement:
if (products[i].name === targetName) {
• Checks if the name of the product at index i matches the targetName.
• products [i]: Accesses the product object at index i in the array.
• .name: Gets the name property of the current product.
• ===: Ensures a strict comparison (type and value must match).
Purpose: To determine if the current product is the one being searched for.
❖ return statement:
return products[i].price;
198|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
• If the if condition is true, this returns the price of the found product.
• products[i].price: Accesses the price property of the matched product.
Purpose: To immediately stop the function and output the price when the product is
found.
}
❖ End of if block:
Closes the condition that checks if the product is found.
return "Product not available";
return statement:
• If the loop completes without finding the product, this statement is executed.
• Returns a message saying the product is not in the array.
Purpose: To handle cases where the product does not exist in the list.
[Link]("Price of Laptop:", linearSearch(products, "Laptop")); // Output: 1200
[Link]("Price of Monitor:", linearSearch(products, "Monitor")); // Output: 300
[Link]("Price of Tablet:", linearSearch(products, "Tablet")); // Output: Product
not available
[Link]:
Prints the result of calling linearSearch for different product names to the console.
Examples:
linearSearch(products, "Laptop"): Searches for "Laptop" and prints its price (1200).
linearSearch(products, "Monitor"): Searches for "Monitor" and prints its price (300).
linearSearch(products, "Tablet"): Searches for "Tablet" (not in the list) and prints
"Product not available".
Purpose: To test the function with different inputs.
Overall Explanation
• The linear search function goes through each product in the array until it finds the
one that matches the name or finishes checking all products.
• Output:
If the product is found, its price is returned.
If not found, a message ("Product not available") is returned
199|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
2. Binary Search
// Pre-sorted product data
const products = [
{ name: "Headphones", price: 100 },
{ name: "Keyboard", price: 50 },
{ name: "Laptop", price: 1200 },
{ name: "Monitor", price: 300 },
{ name: "Mouse", price: 25 },
];
// Example Usage
[Link]("Price of Laptop:", binarySearch(products, "Laptop")); // Output:
1200
[Link]("Price of Monitor:", binarySearch(products, "Monitor")); //
Output: 300
[Link]("Price of Tablet:", binarySearch(products, "Tablet")); // Output:
Product not available
200|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Program explanation
Input Data:
• The products array is already sorted by name in ascending order.
• Each object has two properties: name and price.
Function:
• left: The starting index of the search range.
• right: The ending index of the search range.
• mid: The middle index of the current range ([Link]((left + right) / 2)).
Algorithm Steps:
• Step 1: Check if the middle product's name matches the target
(products[mid].name === targetName).
• Step 2: If the target name is alphabetically after the middle (products[mid].name
< targetName), move the left pointer to mid + 1.
• Step 3: If the target name is alphabetically before the middle
(products[mid].name > targetName), move the right pointer to mid - 1.
• Step 4: Repeat until the left pointer exceeds the right pointer or the product is
found.
Return Value:
• Returns the price if the product is found.
• Returns "Product not available" if the product is not in the list
201|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Application of learning 3.1.
Hasha Ltd is facing challenges in managing its warehouse data due to the use of hard
copies for record-keeping. As a solution, you have been tasked with creating an efficient
data management system that handles imports, exports, and transit processes for
furniture. Use the following data structures: Stack, Sorting, and Linked List to develop
the system.
For each question below, Write JavaScript code that addresses the respective problem:
1. The company receives shipments daily, and the manager needs to process them in
the order they arrive. Sometimes the manager needs to undo the last action
(removal of incorrect shipments). Write JavaScript code using a Stack to manage
this process. The stack should allow the manager to undo the last operation
efficiently. Define the methods needed to push, pop, and check the top of the stack.
2. The warehouse manager needs to sort furniture items by categories such as Tables,
Chairs, Beds, and Dressers to produce a daily report. Write JavaScript code using a
Sorting Algorithm to organize these categories.
3. The number of shipments in the warehouse can vary daily, so a flexible data
structure is needed. Write JavaScript code using a Linked List to represent the
furniture items in the warehouse, allowing dynamic addition and removal of items.
202|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Indicative content 3.2: Run JavaScript Source Codes
Duration: 20 hrs
✓ Rendering engine
A rendering engine is a software program that interprets and converts the HTML,
CSS, and JavaScript code of a web page into visuals that are displayed on the
screen. It is the core component of a web browser and plays a crucial role in the
overall performance and compatibility of the browser.
Benefits of Rendering Engines
The benefits of Rendering engines are:
203|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Works Everywhere: Don’t worry about Windows, Mac, or Linux – rendering
engines speak the language of all devices, making sure websites work
flawlessly regardless of your setup.
Modern Goodies: Think of fancy animations, 3D graphics, and cool new
features. Rendering engines are always learning, constantly adding support
for the latest and greatest web technologies.
Your Browser, Your Way: Some engines love customization! They let you
tweak your browser to your liking, adding extensions, and themes, and even
building entirely new things. It’s like having a toolbox for your browser! Tasks
performed by Rendering Engines in Browsers The various task performed by
Rendering Engines are:
Creating DOM tree: The rendering engine’s parse the HTML code of the web
page.
This involves breaking down the HTML elements and their attributes into a the
Document Object Model (DOM) tree. The DOM tree is a hierarchical
representation of the web page’s content.
Appling styles: The rendering engine parses the CSS styles of the web page.
CSS rules such as font styles, colors, margins, and positioning define how
HTML elements should be visually presented, . The rendering engine
applies these styles to the DOM tree, transforming the structural
representation into a styled representation.
Layout Construction: Once the DOM tree is styled, the rendering engine
enters the layout phase. It calculates the exact position and dimensions of
each element on the screen. Some complex layout algorithms are used for
calculating the relationships between elements such that the web page’s
content is displayed as intended by the developer.
DOM to pixels: The rendering engine starts the rasterization stage where
it converts the vector-based DOM tree into a grid of pixels. Each pixel is
assigned a color with respect to the element. This results in a rasterized
image representation of the web page.
Pixels to Display: The compositing is then done where the rasterized image
is layered on top of other visual elements such as the background and
browser controls. Compositing make sure that the visual elements are
correctly blended and displayed on the screen.
GPU for Rendering: To enhance performance, modern rendering engines
uses Graphics Processing Unit (GPU). The GPU is a specialized hardware
component designed to handle graphics-intensive tasks efficiently. By
allowing rasterization and compositing process to the GPU, rendering
204|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
engines can significant improve its performance. This feature allows
smoother and more responsive web browsing experiences.
Optimizing: Rendering engines are constantly evolving, undergoing
continuous optimization to enhance performance, compatibility, and
maintain web standards. Developers improve the efficiency of algorithms,
reduce memory usage, and ensure compatibility with the latest web
technologies.
✓ Rendering Engines of Web Browsers
There are three primary rendering engines that power the majority of web
browsers today:
Blink: Blink is an open-source rendering engine developed by Google and
is the foundation for the Chrome browser. It is also used by several other
browsers, including Opera, Brave, and Vivaldi.
Gecko: Gecko is another open-source rendering engine developed by
Mozilla and is the engine that powers the Firefox browser. It is known for
its adherence to web standards and strict compatibility with various web
technologies.
WebKit: WebKit is an open-source rendering engine initially developed by
Apple for its Safari browser. It is also used by the iOS version of the Chrome
browser and serves as the basis for the Qt WebEngine framework.
EdgeHTML: EdgeHTML, a fork of Trident (Internet Explorer’s engine), is
Microsoft’s
Rising star. It’s known for its focus on interoperability and compatibility with older
web technologies while embracing modern advancements. Think of it as a bridge
builder, connecting the past and present of the web, ensuring smooth transitions
for users and developers alike.
Other Engines: Beyond these giants, a constellation of niche engines exists,
catering to specific needs and platforms. WebKit variations like Presto (Opera
Mini) and Goanna (Vivaldi) offer unique mobile experiences. WebRender (Android
WebView) prioritizes efficiency on low-powered devices. Each engine, like a
specialist chef, brings its own flavor and expertise to the table, enriching the web’s
diversity and adaptability
205|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Microsoft Edge Blink
Opera Blink
Brave Blink
206|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
6. JSFiddle
7. CodePen
8. Observable
9. Aptana
10. Amazon Web Services9,
Points to Remember
• Browser embedded tools are features or functions integrated directly into a web
browser, providing additional capabilities beyond the basic browsing experience.
• The main component of browser embedded Tools include Rendering engine and
Web dev tools
As software developer install a browser and JavaScript IDE terminal into your
computer and write JavaScript codes that display Hello Word, using browser
embedded Tools.
207|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Indicative content 3.3: Test Time and Space Complexity
Duration: 15 hrs
208|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
• Big-O Notation: This is the standard way to express time complexity. It
represents the worst-case scenario of an algorithm’s growth rate relative to the
input size (n). Common Big-O time complexities include:
✓ O(1): Constant time – the execution time does not change regardless of
input size.
✓ O(log n): Logarithmic time – the time increases logarithmically as input
size increases.
✓ O(n): Linear time – execution time grows proportionally to input size.
✓ O(n²): Quadratic time – time grows with the square of the input size.
✓ O(2^n): Exponential time – the time doubles with each additional input
element.
• Best-case, Worst-case, and Average-case:
✓ Worst-case: The maximum time the algorithm takes for any input.
✓ Best-case: The minimum time, often when the input is already optimized
(e.g., sorted).
✓ Average-case: The expected time, considering all possible inputs and
probabilities.
1.2. Space Complexity
Space complexity measures the amount of memory or storage an algorithm uses
as the input size grows. Like time complexity, it is expressed in Big-O notation.
• Auxiliary Space: Refers to the extra space or temporary storage used by
the algorithm, excluding the input data itself.
• In-place algorithms: These algorithms use a minimal amount of extra
memory, typically O(1), as they modify the input data directly.
1.3 Trade-offs Between Time and Space
In many cases, optimizing for one complexity may worsen the other:
• Time-space trade-off: Some algorithms consume more memory to
reduce time, while others take longer but use less memory. For example:
✓ Merge Sort (O(n log n) time, O(n) space) uses extra space for sorting.
✓ Quick Sort (O(n log n) time, O(log n) space) uses less space but may be
slower on certain inputs.
2. Time and Space Measurement Tools
Measuring these complexities is important for optimizing and ensuring the
efficiency of code. Various tools are available to aid in profiling and benchmarking
code execution.
Below are the key tools for measuring time and space complexities in JavaScript:
Profiling Tools, [Link], Benchmarkify and jsPerf
209|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
1. Profiling Tools:
Profiling tools allow developers to collect detailed data about the runtime
performance of an application. They provide insight into function call durations,
memory usage, and possible performance bottlenecks.
✓ Chrome DevTools: One of the most commonly used tools for JavaScript
profiling. It helps visualize call stacks, memory allocation, and heap
snapshots.
✓ [Link] Profiler: Offers built-in profiling features to measure both time
and space complexity in [Link] environments.
2. [Link]:
[Link] is a powerful JavaScript benchmarking library designed to
measure the execution time of code with high precision. It can handle
asynchronous benchmarks and automatically account for fluctuations in the
system load, giving accurate results.
✓ Supports comparative benchmarking of multiple code snippets.
✓ Can be run both in browsers and [Link] environments.
✓ Built-in functions for managing test cases, suites, and statistical analysis.
3. Benchmarkify:
Benchmarkify is a minimalistic benchmarking framework designed for
[Link]. It simplifies the process of comparing performance between
multiple functions or implementations.
✓ Provides an easy API for creating and running benchmarks.
✓ Capable of comparing different algorithms or code implementations.
✓ Supports asynchronous benchmarks, which makes it a good fit for
performance testing in complex environments.
4. jsPerf:
jsPerf is an online platform that allows developers to create and share
JavaScript performance tests. It lets users test the performance of different
approaches to solve a problem by comparing execution speeds.
✓ Allows for easy performance comparison of different code snippets in a
collaborative manner.
✓ Provides access to real-world browser environments for accurate
measurements.
✓ Suitable for testing browser-specific behaviors, which is especially useful
for front-end developers.
210|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Practical Activity 3.3.2: Testing the program performance.
Task:
Develop a simple web page and Test its Time and space complexity, and finally
document test findings.
2: Follow the demonstration of trainer
3: Individually perform the task 3.3.2 referring to the demonstration
4: Ask for assistance where it is needed.
5: Read the key readings 3.3.2 in trainee’s Manual
211|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Navigate to the "Performance" panel. You can capture a snapshot of all the actions
on the webpage for a certain period by clicking the record button at the top left of
the panel. While recording, interact with your web page in a way that triggers the
JavaScript operation you're interested in, then stop recording.
After that, DevTools will provide a comprehensive breakdown of everything that
happened, including JavaScript execution, painting, layout, system, and loading.
Look for long bars in the “Main” row for possible inefficiencies. Additionally, you
can click on these bars to get more detailed information.
Step 3: Use the Profiler Panel
Another tool useful for checking JavaScript execution time is the "JavaScript
Profiler" panel. In this panel, you can start a new CPU profiling by clicking the Start
button. After collecting the profile data, stop recording.
[Link] Test Findings
When documenting your findings, include the following:
• Purpose: State the purpose of the benchmark (e.g., comparing data structure
performance).
• Test Setup: Describe the environment, input sizes, and specific operations tested.
• Results: Include the measured time and memory usage. Use tables or graphs for
clarity.
• Analysis: Interpret the results. Discuss which data structure performed better
and why.
• Conclusions: Summarize the findings and any recommendations for future
implementations.
Example Documentation Structure
Title: Performance Testing of JavaScript Data Structures
Purpose: To compare the performance of arrays vs. linked lists for insertion
operations.
Test Setup:
• Environment: [Link] v14
• Input Size: 1,000 elements
• Operations: Insert 1,000 elements into an array and a linked list.
212|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Results
Data Time Memory
Structure (ms) Usage (MB)
Array 5 2
Linked List 12 3
Analysis: The array performed faster for insertions due to contiguous memory
allocation, while the linked list used more memory because of node pointers
Points to Remember
DF TSS is a TVET school that has a new school management system. Before its use, the
school need software engineer to test for them the developed system and document test
findings.
213|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
Learning outcome 3 end assessment
Written assessment
I. Read the following statement related to data structure and algorithm
fundamentals, and answer True if the statement is correct and False if the
statement is wrong:
1. The bubble sort algorithm is generally faster than quick sort for large
datasets
2. Arrays and linked lists are both linear data structures
3. Binary search can be performed on both sorted and unsorted arrays
4. [Link] and jsPerf are tools used for testing and measuring the
performance of JavaScript code.
5. Profiling and benchmarking tools like [Link] and jsPerf help evaluate
the performance of JavaScript code.
II. Read the Read the following statement related to data structure and algorithm
fundamentals and choose the letter corresponding to the correct answer.
1. Which of the following environments can be used to run JavaScript source code?
a) Browser Developer Tools
b) IDE Terminal
c) Text Editor
d) Both a and b
2. Which of the following is a linear data structure?
a) Graph
b) Tree
c) Linked List
d) Hash Table
3. Which sorting algorithm generally has better average performance on large
datasets?
a) Bubble Sort
b) Quick Sort
c) Insertion Sort
d) Selection Sort
4. When can binary search be used?
a) On unsorted data
b) On sorted data
c) On linked lists only
d) On any data structure
214|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
5. Which of the following tools is commonly used to profile and measure JavaScript
performance?
a) Chrome DevTools
b) jsPerf
c) [Link]
d) All of the above
Practical assessment
Hasha Ltd is facing challenges in managing its warehouse data due to the use of hard
copies for record-keeping. As a solution, you have been tasked with creating an efficient
data management system that handles imports, exports, and transit processes for
furniture. Use the following data structures: Stack, Sorting, and Linked List to develop
the system.
For each question below, Write JavaScript code that addresses the respective problem:
I. The company receives shipments daily, and the manager needs to process them in
the order they arrive. Sometimes the manager needs to undo the last action
(removal of incorrect shipments). Write JavaScript code using a Stack to manage
this process. The stack should allow the manager to undo the last operation
efficiently. Define the methods needed to push, pop, and check the top of the stack.
II. The warehouse manager needs to sort furniture items by categories such as Tables,
Chairs, Beds, and Dressers to produce a daily report. Write JavaScript code using a
Sorting Algorithm to organize these categories.
III. The number of shipments in the warehouse can vary daily, so a flexible data
structure is needed. Write JavaScript code using a Linked List to represent the
furniture items in the warehouse, allowing dynamic addition and removal of items.
END
215|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
References
BOOKS
javatpoint. (2024). /javascript-queue. Retrieved from javatpoint:
[Link]
WEB LINKS
educative. (2024). /blog/data-strucutres-hash-table-javascript . Retrieved from
educative: [Link]
216|D a t a S t r u c t u r e a n d A l g o r i t h m F u n d a m e n t a l s – T r a i n e e
Manual
1 |D a t a S t r u c t u r e and Algorithm Fundamentals–Trainee
Manual
October
Mm, YYY2024