0% found this document useful (0 votes)
231 views105 pages

Data Structure and Algorithms Module

Here are some examples of implementing primitive and composite data types in C++: // Primitive data types int x = 10; // integer char letter = 'a'; // character float num = 3.14; // floating point number bool isTrue = true; // boolean // Composite data types // Array int numbers[5] = {1, 2, 3, 4, 5}; // String string name = "John"; // Struct struct Student { string name; int age; float gpa; }; Student student1; student1.name = "Jane"; student1.age = 20; student1.gp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
231 views105 pages

Data Structure and Algorithms Module

Here are some examples of implementing primitive and composite data types in C++: // Primitive data types int x = 10; // integer char letter = 'a'; // character float num = 3.14; // floating point number bool isTrue = true; // boolean // Composite data types // Array int numbers[5] = {1, 2, 3, 4, 5}; // String string name = "John"; // Struct struct Student { string name; int age; float gpa; }; Student student1; student1.name = "Jane"; student1.age = 20; student1.gp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 105

DATA STRUCTURES AND ALGORITHMS

TABLE OF CONTENTS

I. Chapter 1 – Abstract Data Type and Recursion


A. Abstract Data Type 6
B. Data Structure 10
C. Algorithms 12
D. Recursion 16
II. Chapter 2 – Computational Complexity
A. The Empirical and Theoretical Method 20
B. The Input 23
C. The Process 27
D. The Big-O Notation 30
III. Chapter 3 – Stacks
A. Introduction to Stacks 35
B. Stack ADT Representation and Implementation 39
C. Stack Application: Polish Notation 42
IV. Chapter 4 – Queues
A. Introduction to Queues 46
B. Queues ADT Representation and Implementation 50
V. Chapter 5 – Linked Lists
A. Nodes and Linked List 55
B. Singly Linked List 58
C. Doubly Linked List 62
D. Circular Linked List 65
VI. Chapter 6 – Trees
A. Definition and Related Terms 68
B. Binary Tree 70
C. Ordered Binary Tree Implementation 72
D. Binary Tree Traversal 75
VII. Chapter 7 – Binary Search Tree
A. Binary Search Tree 82
B. Binary Search Tree – Search Operation 84
C. Binary Search Tree – Insert Operation 87
D. Binary Search Tree – Deletion Operation 90
VIII. Chapter 8 – Heaps
A. Introduction to Heaps 94
B. Heaps For Priority Queues 96
C. Heaps for Sorting 99
IX. Chapter 9 – Graph
A. Graph ADT Specificartion 103

2
MODULE OBJECTIVES:
1. Design, implement, test and debug program based on a given specification that
uses and implements abstract data types.
2. Argue strengths and weaknesses among multiple implementations.

3
CHAPTER 1: ABTRACT DATA TYPE AND RECURSIONS

Objectives: At the end of this Chapter, the student should be able to:
1. Discuss the concept and the stages of an ADT
2. Build data structure using primitive data types
3. Determine the good properties of good algorithm
4. Design and implement recursive algortihm

A. Abstract Data Type


At the end of this topic the student is expected to:
 Define data and ADT
 List the stages of ADT
 Explain what will happen in every stages of ADT

We begin solving computational problems by identifying first the data and the
operation to these data. Data are information gathered to express knowledge about a
world or an environment. Data are raw facts like your name, course, year and department.
These data are controlled by operations so that they can be discussed, explain and
calculated.
It is important to identify the data before they can be manipulated. We need to
identify its components, properties (data type) and the operations to be performed on this
data. The process of modelling and describing the data is called abstract data type.
An Abstract Data Type or ADT gone through three stages:
 Specification
 Representation
 Implement

Specification answer the question what. What are the components of these data?
What are the properties? What are the operations needed on these data to solve the
problem? In short we identify on this stage what are involved in the problem.
Representation answers the question how. How to store these data? The result of
this stage is what we called a data structure. On this stage we must systematically
organize our data in order to use it efficiently. We may use primitive data types or
predefines data structures and it depend if it is available on the programming language to
use.
Implementation shows how to process the data or the procedural description how
each operation is carried using the selected data structure. At this stage algorithm is
formulated and can be written using pseudo code or a specific programing language.

4
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:___________________________________________________ Date:_____________
S.Y./Semester:_______________________ Course and Year:_______________________

Exercise 1.1: Identification.


Determine what stage of ADT the following statement occurs. On the space provided
before each number write S for specification, R for Representation and I for
Implementation.
________ 1. List of students.
________ 2. Java.
________ 3. Use primitive data type.
________ 4. The algorithm to determine the average grade.
________ 5. A pseudo code to determine the student with highest average.
________ 6. Get the average grade of the student.
________ 7. C++.
________ 8. Use composite data type.
________ 9. Determine the student with highest average grade.
________ 10. Use array as data structure.

5
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 1.1a: Specification, Representation and Implementation.


Solve the problem below by undergoing three stages of ADT. Write your answer on the
space provided after the problem.
1. How to determine the product with the highest sales?

6
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 1.1b: Self-Help Task.


Research the following topics. Write your answer on the space provided after each
statement.

1. Why we need data structure?

2. Data Structure Interface.

3. Characteristics of a data structure.

7
B. Data Structure

At the end of this topic the student is expected to:


 Define data structure
 Give example of primitive data types
 Give and explain the example of composite data types.

Data Structure is a systematic way to organize data in order to use it efficiently.


It shows relationship among the data items using primitive structures or other data
structures available in a programming environment.
Data structure is very important that it affects the needed space to store the ADT
and the efficiency on the algorithms to solve the problem. In programming the data
structure it uses primitive data types for simple data structure while composite or user
defined data types is used for complex one.
Primitive data types are the boolean, integer, character, and float. These data
types are almost available in every programming language. These are also data structure
of an ADT because there is policies on how their instance are stores and accessed.
The following are the example of composite data types.
 Array
 Strings
 Structs
 Classes
Array allows data of the same to be organized in a single variable. Each data is
organized in index, starts from 0 to a given size of an array. Some arrays are
multidimensional.
Strings are sequence of characters and have length. Some of the operations of
strings are getting the substring, converting to upper case and many more.
Structs grouped data as one data type and its instance can be created. Structs is
available in almost all programming language including C and C++.
Classes combine operations and data as single data type. You are familiar with
classes as it is already introduces to you in your freshmen year. An instance of class is
called object and is available to any object-oriented programming language.

8
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 1.2: Programming Activity


1. Implement the primitive data types and composite data types on the programing
language of your own choice including instances.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

9
C. Algorithms
At the end of this topic the student is expected to:
 Explain and give example of algorithm
 List and Define the properties of a good algorithm
 Write subroutine algorithm

In order to solve computational problem after specifying and representing the data
it needs a procedure or set of instruction called algorithm. Algorithm is a well-defined
procedure that processes input values to generate desired output values to solve a
problem. Algorithm is language independent and can be implemented to any
programming languages.
Not all procedure can be called algorithm. Algorithm must have the following
properties:
 Input
 Output
 Definite
 Effective
 Finite
 Correct
 General
 Efficient

All algorithms must have input or the instance of the problem you want to solve,
it must also show output or the result. Each step in the algorithm must clear and
unambiguous including the input/output and must execute as expected. It should be
terminated after a finite number of steps. Even though it will produce result it must
correct and desirable to all valid input or instances. Most of all it will solve the problem
with less resources needed such as time and space. Below is an example design of
algorithm that adds two number and display the result:
step 1 − START
step 2 − declare three integers a, b & c
step 3 − define values of a & b
step 4 − add values of a & b
step 5 − store output of step 4 to c
step 6 − print c
step 7 − STOP

There many ways to write your algorithm you can use the natural language such
as English or described it using the programming languages you choose. You may also
combine the English with the basic programming language construct known as pseudo
code.
There are problems that is bigger and that needs bigger algorithm. You may
invoke one or more predefined to break to smaller subtask to solve the sub-problem. The
data structure together with your algorithm will now form our program.
An algorithm can be a function that perform calculation and may return values.
Below is an example of an algorithm to get the sum of two number with a subroutine
called “sum”.
1. z=0
2. sum (24,37)
3. print (“sum of 24 and 37 is “, z)
4. end
5.
6. Void sum(integer x, integer y)
7. {
8. z=x+y
9. }

10
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 1.3: Algorithm


Design an algorithm to solve the following problem. Write your answer on the space
provided.(Attached extra sheet if needed)
1. Given an array of n integers in a random order, write an algorithm that sorts the
integer is ascending order.

11
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 1.3a: Programming Activity


1. Implement the algorithm you design in exercise 1.3 using the programming
language of your own choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

12
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 1.3b: Self-Help Task.


Research the following topics. Write your answer on the space provided after each
statement.
1. Describe an algorithm that is not generally correct

2. Describe an algorithm that is not definite.

3. Describe an algorithm that is finite but not efficient.

13
D. Recursion
At the end of this topic the student is expected to:
 Explain recursion
 Explain how chain forms
 Write an recursive algorithm

Remember that one of the basic statements in computer programming is the


looping statements. The statement inside its body is execute more than once and is called
iteration. This is also possible with functions or procedure that programming languages
allows calling itself. The procedure of calling itself forms a chain. An example of a
function or procedure that calling itself:

int function(int value) {


if(value < 1)
return;

function(value - 1);

printf("%d ",value);
}

The process of forming a chain of calls that occur at least twice on the procedure
is said to be recursive and known as recursion. Sometimes two procedures (A and B)
may call each other vice versa this procedure is called mutually recursive.
Recursion is useful when the problem to be solved involved a countable number
of items. It allows reuse of some steps of algorithms and solves something in terms of
smaller parts of that something. One the problem that can be solved by recursion is the
factorial. The following pseucode computes the factorial of n using the recursion.

1. Integer factorialR(n: a non-negative integer){


2. If n=0 then return 1
3. Else return n * factorialR(n-1) // recursive step
4. }

If n is 4 then the output is 24.

14
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 1.4: Self-Help Task.


Research the following topic. Write your answer on the space provided after each
statement. (Attached extra sheet if needed)
1. What is Tower of Hanoi problem? Illustrate or explain how it works and give the
algorithm to solve this problem.

15
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 1.4a: Programming Activity


Implement using recursive subroutines, the following problem in a programing language
of your own choice.
1. Given a positive integer n, print all the integers from 1 to n in ascending order
2. Given a positive integer n, print all the integers from 1 to n in descending order

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

16
References:

Delfinado, Cecil Jose. Data Structures and Algorithms. C & E Publishing, Inc. 2016
https://www.tutorialspoint.com/data_structures_algorithms/index.htm

17
CHAPTER 2: COMPUTATIONAL COMPLEXITY

Objectives: At the end of this Chapter, the student should be able to:
1. Argue the importance of theoretical method of analysing the efficiency of the
algorithm
2. Explain the impact of the input on the computational complexity of algorithms.
3. Explain the Big-O notation.

A. The Empirical and Theoretical Method


At the end of this topic the student is expected to:
 Explain the empirical method
 Explain the theoretical method
 Defend why theoretical method is the best approach to use

Of all the properties of algorithms correctness and generality is the most


important. It must produce the desired result to solve the problem on all valid inputs.
Efficiency of an algorithm though comes second but still very important. Efficiency
refers to the resources such as time and space an algorithm needed to solve the problem.
The algorithms the uses the lesser resources are regarded as more efficient. Algorithms
that can solve same problems are often compared.
The question is how to measure the efficiency of an algorithm? You may do it by
implementing the algorithms in some programming language and run it then measured
the time elapse between them from start to completion. There are also tools that could
analyse how many times each program lines. This method is called Empirical Method of
analysing the efficiency of an algorithm. But this method has many factors that affect the
performances of the algorithm. It includes the programming language use, computer
processor, memory and other factors. It will give you different result.
To measure the efficiency of the algorithm it must language-independent and
machine independent. This mean that algorithm must not be actually executed rather
must take theoretical units of time and space consume. This is now the theoretical
method in analysing the efficiency of the algorithm. The results are based solely on the
way algorithm solve the problems and not influence by the poor processor, more cache
memory, or a multi-user environment.
The theoretical method is useful when you compare algorithms to determine the
algorithm that run faster and take less space or the more efficient algorithm. In the later
topic we will analyse the efficiency of algorithms and we will use the theoretical method
as the approach.

18
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:_____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 2.1: Empirical or Theoretical


On the space provided before each number write E if the statement is an Empirical
method or T for Theoretical.
________ 1. Use of automated profiling tools to analyse the algorithm.
________ 2. Rerunning the program may give different measurements.
________ 3. The algorithm is language independent.
________ 4. The analysis is more controlled.
________ 5. The variable of an experiment must be limited and controlled.
________ 6. The algorithm is machine dependent.
________ 7. Dependent only on its input, process and output.
________ 8. Measure the time elapse from start to completion.
________ 9. Detach from any run time environment.
________ 10. Check the memory utilization while the program is running.

19
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:_____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 2.1a: Self-Help Task.


Research the following topics. Write your answer on the space provided.
1. What is algorithm Space Complexity?
2. What is algorithm Time Complexity?

20
B. The Input
At the end of this topic the student is expected to:
 Define what is input size
 Explain the impact of input size in analysing the algorithm
 List and explain the three cases in analysing the time complexity of the
algorithm

To compare the algorithms the can solve same problem, should be given the same
input and input size, and the analysis must base solely for that input. The size of the input
is one of the factor to determine the time and space needed by an algorithm to execute.
The more input the more time and space an algorithm takes to process.
Algorithms performance was put to test when the input size is large enough. An
algorithm that is more efficient is exhibit when the size increases. Even with size
becomes sufficiently large there are algorithm that will more efficient than others. The
behaviour of this algorithm is called computational complexity of algorithms.
Algorithm time complexity is evaluated using three cases:
 Best case
 Average case
 Worst case
The algorithms run fastest on the best case. But take note that when it is fast,
clients seldom provide positive response. In average case we analysed algorithm base on
its average performance by determining the statistical mean of the algorithms
performance over all possible inputs. However, average performance is difficult to
compute. That is why algorithm is more often evaluated using the worst case input. It is
often most useful because it gives a guarantee that your algorithm will not behave any
worse.

21
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:_____________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 2.2: True or False.


On the space provided before each number write T if the statement is true, F if false.

________ 1. To compare fairly algorithms must be given same input.


________ 2. It is wise to compare algorithms with different input size.
________ 3. Algorithm inefficiency is magnified when the size is large enough.
________ 4. Algorithm superiority becomes apparent when input size is small.
________ 5. Computational complexity also applies when the input size.
________ 6. Algorithm may have different runtimes for inputs of the same size.
________ 7. An algorithm‟s worst case could be the best case input of another.
________ 8. Many programs are judged on their average case.
________ 9. The average performance may or may not correspond to an actual input.
________ 10. Algorithm is rarely evaluated on its best case.

22
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 2.2a: Self-Help Task.


Research the following topics. Write your answer on the space provided after each
statement.

1. Research the following algorithm and assess their performance using the three
cases on time complexity.
a. Bin Sort

b. Counting Sort

23
c. Quick Sort

d. Selection Sort

24
C. The Process
At the end of this topic the student is expected to:
 List the basic algorithm components
 Define the basic algorithm components
 Give example on each basic algorithm components

As a designer of an algorithm you have no control over the input. You work is to
make sure that it is effective to all valid inputs. But the process applied to these input to
produce the expected output is within your control.
To analyse the time complexity of the algorithm we need to break it down into its
components parts as follows:
 Basic statements
- Declarations, assignments, input/output and the like. They require at most
some constant units of time.
 Expression
- Arithmetic and logical operations, comparisons, concatenation and the
like.
 Block
- The sequence of statement.
 Conditional statement
- The if, case and switch statements and the like.
 Looping statement
- Include for, repeat-until, while-do, do-while loops and the like.
 Procedural calls
- Functions or subroutines calls within the recursive or non-recursive.

25
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 2.3: Identification.


Using the algorithm below, identify the components parts. Write your answer on the
space provided.

Integer LRSearch(x: key; A[1..n]: array with n integers)

1. i=1
2. while (i < n and x ≠ A[i])
3. i=i+1
4. If (i < n
5. then return i
6. else return 0

1. Basic statements

2. Expressions

3. Blocks

4. Conditional statements

5. Looping statements

6. Procedural call

26
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 2.2a: Programming Activity


1. Develop a program that has all the component parts discussed above. Use the
programing of your own choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

27
D. The Big-O Notation.
At the end of this topic the student is expected to:
 Define Big-o notation
 List and explain the classes of Big-O
 Identify the classes of the algorithm

The big-O or big-Oh notation is an upper bound to the computational complexity


of an algorithm and it measures the growth of functions. It rates algorithms into widening
efficiency groups or classes shown below.

Big-O Name Description


O(1) Constant A few operations whose number is independent of
the input size are executed.
O(lg n) Logarithmic The problem size is repeatedly reduced by a
fraction of the previous size.
O(n) Linear A few operations are performed on each input
element.
O(n lg n) Super linear A problem, is partitioned into subproblems, and
the solutions are combined to solve the original
problem
O(n2) Quadratic A fraction of all pairings of data is processed.
O(n3) Cubic A fraction of all triples of data is processed.
O(2n) Exponential A fraction of all subsets of data is processed.
O(n!) Factorial A fraction of all arrangements of data is processed.

Example below is an algorithm with O(n2) class.

Integer exAlgo1(a[1..n])
1. maxSum=0
2. for i=1 to n
3. thisSum=0
4. For j=i to n
5. thisSum=thisSum + A[j]
6. If(thisSum > maxSum)
7. maxSum=thisSum
8. Return maxSum

Example below is an algorithm with O(n) class.

Integer exAlgor2(A[1..n])
1. maxSum = thisSum =0
2. for k=1 to n
3. print(A[k])
4. For j=1 to n
5. thisSum=thisSum+A[j]
6. If (thisSum > maxSum)
7. maxSum=thisSum
8. Return maxSum

28
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 2.4: Self-Help Task.


Research the following topics. Write your answer on the space provided after each
statement.(Attached extra sheet if needed)

1. Graph of relative growth rates of the Big-O complexity classes.

2. Discuss the Linear Search and the algorithm of linear search.

3. Discuss the Binary Search and write the algorithm of Binary search.

29
4. Discuss the bubble sort and write its algorithm.

5. Discuss the merge sort and write its algorithm.

30
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 2.2a: Programming Activity


1. Implement one of your discussed algorithm in exercise 2.2 using the
programming language of your own choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

31
References:

Delfinado, Cecil Jose. Data Structures and Algorithms. C & E Publishing, Inc. 2016
https://www.tutorialspoint.com/data_structures_algorithms/index.htm

32
CHAPTER 3: STACKS

Objectives: At the end of this Chapter, the student should be able to:
1. Describe the stacks ADT and its array representation
2. Implement stack operation
3. Convert expression among infix, prefix and postfix notation.

A. Introduction to Stacks
At the end of this topic the student is expected to:
 Define stack
 List the operation we can do with stack
 Illustrate the stack operation

Stack is a linearly ordered set of elements having the discipline of last-in, first out,
hence it is also known as LIFO list and is accessible only at one end.. It is similar to a
stack of boxes in a warehouse, where only the top box could be retrieved and there is no
access to the other boxes. Also, adding a box means pushing it at the top of the stack.

Figure 3.0
Image source :
https://echolife.files.wordpress.com/2011/09/two_stacks_packing_boxes.jpg

The item at the bottom cannot be pop or delete unless the entire item above it will
be popped out. The following are the operations we can on stack:
 new
 clear
 isEmpty
 isFull
 push
 pop
 peek

The stack can be created and its items can be cleared. Adding item to the top of
the stack is push.

33
Figure 3.1 Push operation
Image source: tutorialspoint.com

Removing the top item of stack is pop operation.

Figure 3.2 Pop operation


Image source: tutorialspoint.com

Peek is getting the top element without deleting it from the stack.

34
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 3.1: Self-help Task.


Write your answer on the space provided after the question.

1. Give a real life example of stacks. Which stack operations do these example
supports exactly?

2. Algorithm for stacks push operation

3. Algorithm for stacks pop operation

35
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 3.1a: Draw/Illustrate.


Illustrate or draw the following sequence of operation on the space provided before each
operations. See Figure 3.1 and 3.2 as a sample illustration.
s= new (stack,4)

1. push (s,‟A‟) 2. Push(s,‟b‟)

3.push (s,‟C‟) 4. Pop(s)

5.push(s,„D‟) 6.pop(s)

7.push(s,„E‟) 8.push(s,„f‟)

36
B. Stack ADT Representation and Implementation

At the end of this topic the student is expected to:


 Determine the data structure for stack
 Explain the algorithm of stack operations
 Implement stack operations

Array is used in to store the stacks. The following defines stacks as a record
containing integer items in array:

stack = record {
maxStksize:integer;
top=integer;
stk=integer[];
}

The highest index of the top item of the array is maxStksize-1. The stack has a
variable that holds the index of the top item, and it becomes top equal -1 when empty.
The following is the new operation for stack integers:

stack new(stack; n){


1. Create instance of the stack record
2. maxStksize=n
3. top=-1
4. stk=new integer[maxStksize]
5. return this new stack

Algorithm to clear stack:

void clear(s: a stack){


s.top=-1
}

isEmpty operation:

boolen isEmpty(s){
if (s.top=-1) then return true
else return false
}

isFull operation:

boolean isFull(s){
if(s.top=s.maxStksize) then return true
else return false
}
push operation:

integer push(s;el:integer){
if (isFull(s)) then return -999
s.top=s.top=1
s.stk[s.top]=el
return 1
}
37
pop operation:

integer pop(s) {
if (isempty(s)) then return -999
integer el=s.stk[s.top]
s.top = s.top-1
return el
}

peek operation:

integer peek(s) {
if (isEmpty(s)) then return -999
else return s.stk[s.top]
}

38
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 3.2: Programming Activity


1. Implement the stack ADT with operations clear, print, isEmpty, isFull, push,pop,
and peek using the programming language of your choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

39
C. Stack Application: Polish Notation
At the end of this topic the student is expected to:
 Evaluate expression using order of precedence
 Explain infix, prefix, and postfix notation
 Convert infix notation to postfix and prefix

Arithmetic expressions are evaluated using the precedence rule called PEMDAS:
 Parenthesis – highest precedence
 Exponent
 Multiplication and Division
 Addition and Subtraction

The parenthesis overrides the precedence. A logician from Poland, Jan


Lukasiewics devised a way to evaluate expression without a parenthesis and is called
Polish Notation and it has two variants:
 Prefix
 Postfix

The natural mathematical expression that we are used to such as “3*(4+10)” is in


infix notation. The expression is in prefix notation if an operator is followed by its first
operand in prefix notation, followed by its second operand in prefix notation. Example:

+67
*8+67

An expression is in postfix notation if the first operand in postfix notation


followed by the second operand in postfix notation followed by the operator of this
operand. Example:

67+
867 + *

In converting an expression to a given notation are arranged from highest to


lowest precedence. Below is an example of converting the expressions “A + B / C – D *
E” an infix notation to prefix and postfix.

Operator First Second Prefix Postfix


operand operand
/ B C /BC BC/
* D E *DE DE*
+ A B/C +A/BC ABC/+
- A+B/C D* E -+A/BC*DE ABC/+DE*-

40
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 3.3: Solving.


Convert the following infix notation to postfix and prefix. Write your answer with your
solution on the space provided.

1. X * ( ( 3 + 4 / Y) – 2 )

2. ( A + B ) / (C – D * E )

41
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Programming Exercises 3.2: Programming Activity


1. Implement the infix to postfix and prefix notation using the programming
language of your own choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

42
References:

Delfinado, Cecil Jose. Data Structures and Algorithms. C & E Publishing, Inc. 2016
Joyce Avestro. (2006). Data Structure. Philippine Society of IT Educators Convention.
https://www.tutorialspoint.com/data_structures_algorithms/index.htm

43
CHAPTER 4: QUEUES

Objectives: At the end of this Chapter, the student should be able to:
1. Describe the Queue abstract data type
2. Design an algorithm using queue
3. Identify application that use queues

A. Introduction to Queues
At the end of this topic the student is expected to:
 Define Queues
 Explain the organization of queues
 List and illustrate the operations on queues

A queue is a linearly ordered set of elements that has the discipline of First-In,
First-Out. Hence, it is also known as a FIFO list. In the rear only new items be added or
enqueued while only in the front may items be removed or dequeued.

Figure 4.0 Real world examples of Queues

The following are the operations on queues:


 New
 Clear
 isEmpty
 isFull
 enqueue
 dequeue
 peek

Enqueue adds an item into the rear of the queue.

Figure 4.1 Enqueue operation on Queue

Dequeue removes the front item from the queue.

Figure 4.2 Dequeue operation on Queue

44
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 4.1: Self-help Task.


Write your answer on the space provided after the question.

1. Identify the similarities and differences between stack and queues.

45
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 4.1a: Draw/Illustrate.


Illustrate or draw the following sequence of operation on the space provided before each
operation. See Figure 3.1 and 3.2 as a sample illustration.
q= new (queue,4)
1. enqueue (q,‟A‟) 2. enqueue (q,‟b‟)

3. enqueue (q,‟C‟) 4. dequeue (s)

5. enqueue (q,„D‟) 6. dequeue (q)

46
7. enqueue (q,„E‟) 8. enqueue (q,„f‟)

47
B. Queues ADT Representation and Implementation

At the end of this topic the student is expected to:


 Design algorithm that will create new item in a queues
 Design algorithm that will enqueu,peek and dequeue an item in queue
 Design algorithm that will check if the queue is empty and full.

Just like stacks array is used in to store the stacks. The following defines queues
as a record containing integer items in array:

queue = record {
maxQsize:integer;
front=integer;
rear=integer;
que= integer [];
}

The highest index of the top item of the array is maxQsize-1. The queue has a
front and rear variables that hold the indices of the first and last items in the queue. When
the queue is empty both the rear and front variables are equal to -1.
The following is the new operation for a queue integers:

queue new(queue;n){
1. Create instance of queue record
2. maxQsize=n
3. front = rear – 1
4. Que = new integer[maxQsize]
5. return this new queue
6. }

Algorithm to clear queue:

void clear(q: a queue){


q.front = q.rear = -1
}

isEmpty operation:

boolen isEmpty(q){
if (q.front=-1) then return true
else return false
}

isFull operation:

boolean isFull(q){
if((q.rear + 1)mod maxQsize=q.front) then return true
else return false
}
enqueue operation:

integer enqueue (q; el:integer){


if (isFull(q)) then return -999
q.rear= (q.rear+1) mod mzxQsize

48
q.que[q.rear]=el
if q.front = -1 then
q.front=0
return 1
}

dequeue operation:

integer dequeue(q){
if(isempty(q)) then return -999
integer el=q .que[q.front]
if q.front =q.rear
then clear()
else q.front=(q.front+1) mod maxQsize
return el
}

peek operation:

integer peek(q) {
if (isEmpty(q)) then return -999
else return q.que[q.front]
}

49
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 4.2: Self-help Task.


Write your answer on the space provided after the question.

1. Real world example of queues application

50
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 4.2a: Programming Activity


1. Implement the queue ADT with operations clear, print, isEmpty, isFull, enqueue,
dequeue, and peek using the programming language of your choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

51
References:

Delfinado, Cecil Jose. Data Structures and Algorithms. C & E Publishing, Inc. 2016
Joyce Avestro. (2006). Data Structure. Philippine Society of IT Educators Convention.
https://www.tutorialspoint.com/data_structures_algorithms/index.htm

52
CHAPTER 5: LINKED LISTS

Objectives: At the end of this Chapter, the student should be able to:
1. Describe the linked lists node ADT and the linked list ADT.
2. Design algorithm that operates on linked lists.
3. Explain the advantages and disadvantages of singly linked, doubly linked and
circular lists.

A. Nodes and Linked List


At the end of this topic the student is expected to:
 Define node and List
 Explain the need to use a linked list for dynamic set of data
 Discuss the properties of a linked list
 List the three types of linked list

To represent data and its relationship among other data, suitable data structure
should be use. To show relationship among data a linked structure is an alternative way
so that an array can store items sequentially.
A List is a sequence of items. It is a static or dynamic set of data that some are
sorted that shows logical ordering. It can be alphabetically or numerically. It is easy for
an array to represent static data, but difficult and time-consuming to maintain for the
dynamic data.
To handle such difficulty for dynamic data, a linked list ADT is theorize to handle
the data operation efficiently. The linked list is made up of nodes that linked to other
nodes.
A node is a container of data. It separates data from other data. It also contains a
pointer to another node. The figure below shows an illustration of a linked list node.

Figure 5.0 Linked List nodes

As shown above a linked list is visualized as a chain of nodes. Each link carries a
data field and a link called next. It has two special pointers:
 Head
 Tail
The pointer that points to the first node is called Head while the tail points to the last
node. They point to null when the list has no first or last node. Though the tail is optional
but it is easy to access the last node if have one.
There three types of linked list:
 Singly Linked List
 Doubly Linked List
 Circular Linked List

53
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 5.1: True or False


Before each number, write T if the statement is correct, otherwise write F.

________ 1. A List is a linear structure.


________ 2. A linked is a good structure to show relationship among data.
________ 3. It is difficult to manage of kinds of list.
________ 4. Array is used to represent linked list.
________ 5. A nodes is contains information about data only.
________ 6. The head is not necessary for a linked list structure.
________ 7. Point to null means no data to linked with.
________ 8. Next is linked the node to other node.
________ 9. To access the last node you need the tail.
________ 10. A link is like a chain.

54
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 5.1a: Self-help Task.


Write your answer on the space provided after the question.

1. What are the operations supported by a linked list node? Define each and give the
algorithm for each operation.

55
B. Singly Linked List

At the end of this topic the student is expected to:


 Define Singly Linked List
 List the operations supported by singly linked list
 Design algorithms that operate in singly linked list.

The first known linked list is the Singly Linked List and is useful to model a
dynamic list for data. The Singly Linked often referred as “linked list”. The nodes are
arranged in a sequence that each node is point to the next node while last node points to
null. The following are the several operations supported by the linked list ADT:
 New
 isEmpty
 toString
 find
 add
 delete

The toString operation returns a string concatenating the information‟s in a linked


list. Find returns a pointer to the first node containing the information if there is.
The data in singly linked list can be represented as a record with head and tail:

Slist=record {
head,tail; snode pointers;
}

The following are the psuedo code for singly linked list operation:
New operation:

slist new(single linked list}{


create instances of slist record
head=tail=null
return this new single linked list
}

isEmpty:

boolen isEmpty (slist1: an slist)


if(slist1.head=null) then return true
else return false
}

toString:

string toString (slist1)


string s=””
snode p=slislt1.head
while (p≠null)
s=s+p.info + “ ”
p=p.next
return s
}

find:

56
snode find (slist1: an slist; el: an integer)
snode p=slislt1.head
while (p≠null and p.info ≠ el)
p=p.next
return p
}

addtoHead:

void addToHead (slist1, el){


slist1.head=new (singly linked list node, el, slist1.head)
if (silist1. Tail=null) then
slist1.tail=slist1.head
}

addtoTail:

void addToTail (slist1, el){


if(isEmpty(slist1)) then
slist1.head=slist1.tail=new (singly linked list node, el,null)
else
slist1.tail.next=new (singly linked list node, el,null)
slist1.tail=slist.tail.next
}

deleteFromHead:

integer deleteFromHead (slist1){


if(isEmpty(slist1)) then return -999
snode1=slist1.head
el=snode1.info
if(slist1.head=slist1.tail) then
slist1.head= slist1.tail=null
else
slist1.head=slist1.head.next
delete(snode1)
return el
}

deleteFromTail:

integer deleteFromTail(slist1){
if(isEmpty(slist1)) then return -999
snode1=slist1.tail
el=snode1.info
if(slist1.head=slist1.tail) then
slist1.head= slist1.tail=null
else
snode p=slist1.head
while (p.next ≠slist1.tail)
p=p.next
slist1.tail=p
slist1.tail.next=null
57
delete(snode1)
return el
}

delete:

integer delete(slist1,el){
if(isEmpty(slist1)) then return -999
if(el=slist1.head.info)then
return deleteFromHead(slist1)
if (el=slist1.tail.infor) then
return deleteFromTail(slist1)
snode pred=slist1.head
snode t = slist1.head.next
while (t ≠ null and t.info ≠ el)
pred=pred.next
t=t.next
if(t = null) then return -999
else
pred=next=t.next
delete(t)
return el
}

58
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 5.2: Programming Activity


1. Implement the Singly Linked List ADT using the operations pseudo code
discussed above using the programming language of your choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

59
C. Doubly Linked List
At the end of this topic the student is expected to:
 Explain Doubly Linked List Structure
 Design an algorithm of the doubly linked list ADT

Singly Linked List can only traversed in head to tail direction or forward manner.
It cannot traverse in opposite direction. Doubly Linked List is a variation of linked
list in which navigation is possible in both ways.

Doubly linked list has an additional previous node pointer. Each prev pointer
points to the previous node. The node at the head has its prev pointer set to null. The
doubly linked list node has the following records structure:

dnode = record {
info:integer;
prev, next; dnode pointers;
}

The operations for doubly linked lists are the same with singly linked lists.
However several operations will be discussed.
New Operation:

dlist new(doubly linked list){


create instance of dlist record
head=tail=null
return this new doubly linked list
}

addToHead operation:
void addToHead(dlist1: a dlist; el: an integer){
if (dlist1.head=null) then
dlist1.head=new (doubly linked list node, el, null, null)
dlist1.tail=dlist1.head
else
dlist1.head=new (doubly linked list node, el, null, dlist1.head)
dlist1.head.next.prev=dlist1.head
}

deleteFromTail Operation:

integer deleteFromTail(dlist1){
if(isEmpty(dlist1) then return -999
d=dlist1.tail
el=d.info
if (dlist1.head=dlist1.tail) then
dlist1.head=dlist1.tail=null
else
dlist1.tail=dlist1.tail.prev
dlist1.tail.next=null

60
delete(d)
return el
}

61
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 5.3: Programming Activity


1. Implement the Doubly Linked List ADT using the programming language of your
choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

62
D. Circular Linked List
At the end of this topic the student is expected to:
 Define and explain circular linked list
 Illustrate the properties if circular linked list
 List the operation on circular linked list

There are lists that are processed in cycle form where after the last item is processed
the first item is processed next. The Circular Linked List is a variation of Linked list in
which the first element points to the last element and the last element points to the
first element. The circular list may be singly or doubly.

Figure 5.0 Singly linked

Figure 5.1 Doubly linked

The nodes in Circular Linked List form a circle where the tail point to the head
node and the prev pointer of the head node points to the tail node. No nodes are pointed
to null but has an external pointer let‟s say cptr instead of head and tail pointer. The
following are the operations in circular linked list:
 New
 isEmpty
 toString
 find
 add
 delete

The add operation adds a node with a given information value before or after the
node pointed by cptr.

63
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 5.4: Programming Activity


1. Implement the Circular Linked List including the toString, find, add, and delete
operations using the programming language of your choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

64
References:

Delfinado, Cecil Jose. Data Structures and Algorithms. C & E Publishing, Inc. 2016
Joyce Avestro. (2006). Data Structure. Philippine Society of IT Educators Convention.
https://www.tutorialspoint.com/data_structures_algorithms/index.htm

65
CHAPTER 6: TREES

Objectives: At the end of this Chapter, the student should be able to:
1. Illustrate tree concepts using appropriate tree terminologies
2. Represent binary tree using linked list
3. Use various tree traversal methods to perform tree operations

A. Definition and Related Terms


At the end of this topic the student is expected to:
 Define tree
 Draw an example of a tree and identify the parts
 Differentiate the parts of the tree

Linked List, stack and queues ADT have linear structure while tree have
hierarchical structures. The tree ADT has a vertex or node, that stores or represent data.
The nodes of the trees are linked together just like the linked list ADT. However the
nodes that are linked are downwards to every other vertex or node. The connection
between a pair of distinct vertices as called edge. The Path refers to the sequence of
nodes along the edges of a tree. Therefore, Tree T= (V,E) is finite set of vertices and a
set of edges E on V such that there is a unique simple path between any pair vertices in
V. Following are the other terms with respect to tree:
 Root – The node at the top of the tree is called root. There is only one root per
tree and one path from the root node to any node.
 Parent −Any node except the root node has one edge upward to a node called
parent.
 Child – The node below a given node connected by its edge downward is
called its child node.
 Siblings – all children of a vertex
 Leaf – The node which does not have any child node is called the leaf node.
 Internal Vertices – non-leaves
 Degree of a Tree – the maximum degree among the vertices in the tree
 Subtree − Subtree represents the descendants of a node.
 Visiting − Visiting refers to checking the value of a node when control is on
the node.
 Traversing − Traversing means passing through nodes in a specific order.
 Levels or depth − Level of a node represents the generation of a node. If the
root node is at level 0, then its next child node is at level 1, its grandchild is at
level 2, and so on.
 Keys − Key represents a value of a node based on which a search operation is
to be carried out for a node.

Figure 6.0 Example of a Tree

66
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 6.1: Identification.


Using the tree below. Identify the following, write your answer on the space provided.

1. Root

2. Parent

3. Child

4. Siblings

5. Leaf

6. Internal Vertices

7. Degree of a Tree

8. Subtree

9. Levels or depth

67
B. Binary Tree

At the end of this topic the student is expected to:


 Explain the binary tree
 Explain how to determine the k-ary of a tree
 Draw a binary tree
 Explain the properties of a Ordered and complete binary tree

The degree of a tree is the maximum degree among the vertices in the tree. If the
degree of a tree is no more than k, the tree is a k-ary tree. If k=2, the tree is a binary
tree. Figure 6.1 is an example of a binary tree.

Figure 6.1 Binary Tree

Figure 6.1 is also an example of Ordered Binary Tree. A binary tree is an


Ordered Binary Tree when the children of each vertex has an ordering (first, second
third… last) often referred as the left and right children.
A Complete Binary Tree is a full binary tree whose leaves are all in the deepest
level.

Figure 6.2 Complete Binary Tree

68
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 6.2: Self-help Task.


Determine the following, write your answer on the space provided after the question.

1. The number of leaves and internal vertices of a binary tree of height 10

2. The number of leaves and internal vertices of a full binary with 1,000 edges

3. The minimum and maximum degrees of a vertex in a 5-ary tree.

69
C. Ordered Binary Tree Implementation
At the end of this topic the student is expected to:
 List the operations on the tree and its vertices.
 Draw an ordered tree node
 Design algorithm of a node

Organizing the data of the ADT tree is important for efficient execution of its
operations. The following are the operations on the tree and its vertices.
 About a tree
o isEmpty(T),numNodes(T),root(T),height(T),tostrin(T)
 About a vertex
o getInfor(n),isLeaf(n), degree(n), levet(T,n),pathFromRoot(T,n)
 Relationship between vertices
o Parent(T,n), firstChild(n), lastChild(n), children((n), nextSibling(T)
 Update tree
o New(tree), setRoot(T, el), setRoot(T,n), deleteNode(T,n), rebalance(T)
 Update new vertex in tree
o New (tree node), addChild (n, el), setLeft(n, el), setRight (n,el),
setInfo(n,el)
To represent the ordered binary tree a linked structure is often used. The nodes
represent the vertex that contains information about the vertex including the pointers to
the left and right children.

Figure 6.3 Ordered Tree using linked list representation

Each node has the following record structure:

btnode = record {
info: integer;
left, right: btnode pointers;
}

70
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 6.3: Self-help Task.


Write your answer on the space provided after the question.

1. Research the pseudo code of the tree operations discussed above. Write your answer
below.

71
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 6.3a: Programming Activity


1. Implement the Ordered Binary ADT with operations discussed above using the
programming language of your choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

72
D. Binary Tree Traversal
At the end of this topic the student is expected to:
 Explain how to traverse a tree
 Use the various tree traversal
 Illustrate how to traverse a tree

Traversing means passing through nodes in a specific order. It walk through the
entire tree going each vertex and each edges. There are many operations implemented by
traversing tree. There two general classes of algorithm that efficiently traverse the trees:
 Breadth-First
 Depth-First

The Breadth means width, in other words we will traverse the tree level-by-level
starting from level 0 to the deepest level. From left to right is how are going each level
before proceeding.
Using the figure below, the Breadth-first sequence is: A B C D E F G H I J K L M

Figure 6.4 Breadth-First Traversal

The Depth-First traversal navigates a tree by proceeding downwards as deep as


possible and backtracks when all subtree of a node have been explored. There three ways
to traverse a tree using depth-first:
 Preorder
 Postorder
 Inorder

In preorder traversal , a node is visited the first time it is encountered before


exploring its subtrees.

Figure 6.5 Pre-order Traversal


Inorder traversal, a node is visited after its subtree has been explored but before
exploring its right subtree.

73
Figure 6.6 Inorder Traversal

Postorder traversal, a node is visited after both its subtrees have been explored.

Figure 6.7 Postorder traversal

74
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 6.4: Traverse.


Traverse the following tree. Identify the sequence using the given ways.
1.

Breath-First Traversal Sequence:

Inorder Sequence:

Preorder Sequence:

Postorder Sequence:

2.

Breath-First Traversal Sequence:

Inorder Sequence:

75
Preorder Sequence:

Postorder Sequence:

3.

Breath-First Traversal Sequence:

Inorder Sequence:

Preorder Sequence:

Postorder Sequence:

76
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 6.4a: Self-help Task.


Write your answer on the space provided after the question.

1. Algorithm of the breadth-first traversal

2. Algorithm of the inorder traversal

3. Algorithm of the preorder traversal

4. Algorithm of the postorder traversal

77
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 6.4b: Discussion.


Write your answer on the space provided after the question.

1. What is syntax tree? How the tree traversal is applied to syntax tree? Discuss
your answer.

78
References:

Delfinado, Cecil Jose. Data Structures and Algorithms. C & E Publishing, Inc. 2016
Joyce Avestro. (2006). Data Structure. Philippine Society of IT Educators Convention.
https://www.tutorialspoint.com/data_structures_algorithms/index.htm

79
CHAPTER 7: BINARY SEARCH TREE

Objectives: At the end of this Chapter, the student should be able to:
1. State the properties of Binary Search Tree Data Structure
2. Explain how these properties enable problems to be solved efficiently
3. Simulate the operations on BST

A. Binary Search Tree


At the end of this topic the student is expected to:
 Define key, values and map or dictionary
 Explain the properties of a binary search tree
 Illustrate an example of a binary search tree

Nodes and records are used to organize the collection of related data. This field
include the key that identify each record uniquely, and the value is the record. A map or
a dictionary is an ADT for collection of key-value pairs. Example of a key-value pair is
your student number is the key while the value is your name, course, and other data. We
can search, insert, delete and changing values of a records using a key are operations we
can do on the map.
The binary search tree is one of the data structures that enable the execution of the
map operations efficiently.
The Binary Search Tree is a binary tree with unique information called keys in
the node and has the following binary search tree properties:
 The key in every node is larger than each of the keys in its left subtree, if any;
 The key in every node is smaller than each of the keys in its right subtree if
any.

Figure 7.0 is an example of a binary search tree that satisfies the above properties.

Figure 7.0 Binary Search Tree Example

80
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 7.1: Illustration


Use the alphabet of your name as keys. Draw a binary search tree on the space provided.

81
B. Binary Search Tree – Search operation

At the end of this topic the student is expected to:


 Design an algorithm to search a key in binary search tree
 Explain the efficiency of binary search tree in searching a key
 Explain how to search a key in binary search tree

Searching using a binary search tree allows you to search a key without traversing
the every node on the tree. It is like the binary search algorithm that sorted first the keys
in the array before searching the key. The following is the algorithm how to search a
binary search tree:

btnode BST-search(T: BST;k:key){


n=T.root
while (n≠null)
if (k=n.key) then
return n
else
if(k<n.key)
n=n.left
else
n=n.right
return null
}

Searching a key must start from the root if it contains the k as the key, then the
search key is found else it will continue the search. If the k is smaller than current node
then it will narrow to its right subtree. On the other hand, if it is larger than the current
node then it will narrow down to right subtree.
For Example consider the binary search in Figure 7.0. the search key k=31. The
search path will go from 27, right to 35 and left to 31 before the k is found.
The number of nodes the search has visited or the search path determines the
running time of the Binary Search Tree search algorithm.

82
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 7.2: Illustration


Using the binary search tree you created in exercise 7.1, illustrate and explain how the
search operation in a BST is done. The key to be search must found on the deepest level
of the tree.

83
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 7.2a: Programming Activity


1. Implement the binary search tree with search operation using the programming
language of your choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

84
C. Binary Search Tree – Insert operation
At the end of this topic the student is expected to:
 Design an algorithm to insert a key in binary search tree.
 Explain how to insert a key in BST
 Give example how to insert a key in BST

Building and growing a binary search keys are inserted. To insert a key in a
binary search the following is the algorithm:

Void BST-inser(T:BST;k:key)
//assume that k is not yet in the tree
If(T.root=null) then
T.root=new(btnode,k)
return
n=T.root
p=null
while (n≠null)
p=n
if (k>n.key) then n=n.left
else n=n.right
if (k<p.key)
then p.left=new(btnode, k)
else p.right=new(btnode, k)
}

A new node will be created if the tree is empty. If the Binary Search Tree is not
empty then it will search the tree from the root down to its insertion point. The n in
the above algorithm is the current node while the p is its parent node. As it travels
down, if the n becomes null the k will be inserted on a left of right of the parent node.
Example, we will the figure 7.0 as our BST. We will insert the key=9 in the tree.
The search would be, 27, 14, 10 then the n becomes null. The parent will be the 10.
Since 9 is less than the parent node p=10 it will be inserted and become the left child
of the node.

85
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 7.3: Illustration


Using the binary search tree you created in exercise 7.1, illustrate and explain how the
insert operation in a BST is done.

86
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 7.3a: Programming Activity


1. Implement the binary search tree with insert operation using the programming
language of your choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

87
D. Binary Search Tree – Deletion operation
At the end of this topic the student is expected to:
 Design an algorithm to delete a key in BTS.

It is easy to insert a key in BST than to delete it. It is more complicated the
inserting. Below is the algorithm to delete a key in BST:

Void BST-delete(T:BST;k:key)
//parent pointer help, if avialble. Else keep track of parents in
searches

N=BST-search(T,k)
If(n=null) then return
p=n’s parent
if n is a leaf then
if p=null then T.root=null
else if p.left=n then p.left=null
else p.right=null

delete node n
if n has only one child then
if p=null then set p.left to only child of n
else if p.left=n then set p.left to only child of n
else set p.right to only child of n

delete node n
if n has 2 children then
find the node m with maximum key in n’s left subtree.
n.key=m.key
if m is a left child then set m’s parent’s left to m.left
else set m’s parent’s right to m.left
delete node m

88
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 7.4: Self-help task


Explain how the deletion operations is done in BST.

89
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 7.4a: Programming Activity


2. Implement the binary search tree with delete operation using the programming
language of your choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

90
References:

Delfinado, Cecil Jose. Data Structures and Algorithms. C & E Publishing, Inc. 2016
Joyce Avestro. (2006). Data Structure. Philippine Society of IT Educators Convention.
https://www.tutorialspoint.com/data_structures_algorithms/index.htm

91
CHAPTER 8: HEAPS

Objectives: At the end of this Chapter, the student should be able to:
1. State the properties of Heaps
2. Explain how these properties enable problems to be solved efficiently
3. Identify situation when heaps data structure is useful

A. Introduction to Heaps
At the end of this topic the student is expected to:
 Define heaps
 Describe a max-heap and min-heap
 Illustrate max-hip and min-heap

A heap is an almost complete binary tree. The key in each node of a heap is better
than the key in its children. But the word “better” interprets differently by the max-hep
and min-heap. It is larger for max-heap hence the root has the largest key and smaller
for min-heap that makes its the smallest key.

Figure 8.0 Min-heap

Figure 8.1 Max-heap

Figure 8.0 shows a min-heaps and Figure 8.1 shows amax-heap.

92
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 8.1: Illustration


Use the alphabet of your name as keys. Draw a max-heap and min-heap on the space
provided below.

93
B. Heaps for Priority Queues

At the end of this topic the student is expected to:


 Explain priority queues
 Explain heaps
 Design an algorithm for max-heap

Remember that the queue ADT has a first-in, first-out organization. Enqueue
item on the rear while Dequeue data from the front thus it is rarely for the items to be
inserted in the middle or at the front of the queue. But there is situation that allows
cutting in the queue. Example is when there is a queue to pay your bills, it is a first come,
first serve basis, if you are on the first you will be entertain first, their certain cases just
like our senior citizens, VIP‟s and others that are allowed to cut in the line. The higher
priority numbers will overtake all items in the queue with lower priority number. Such
queue is called priority queues.
Priority Queues can be represented using array and linked list sorted by priority
number. But for array, it is time consuming, because some items have to be removed
physically. To insert a new item a gap must be create and a gap that a deleted item was
located must be removed. That makes the linked list the better option but on average
case.
The heaps data structure is efficient to use to represent priority queues. If your
priority queues prioritize higher number then it can efficiently represented by max-heap.
To create new max-heap you need to declare and initialize the following variable:

heapSize=0
length=100
A[1…length]

To enqueue an item el into a max-heap, the following is the algorithm:

Integer heapEnqueue (H:max-heap; el:integer){


If (H.heapSize+1 > H.length)
Then retuen -999
H.hepSize=H.heapSize+1
H.A[H.heapSize]=el
heapifyUp(H,H.heapSize)
Return 1
}

Notice in line number 6 that the algorithm heapifyUp, it is called to buble-up the
large key and remedy the violation. The following is the heapifyUp algorithm:

Void heapifyUp(H: a max-heap; k:integer)


el=H.A[k]
while(k>1 and H.A[parent(k)<el){
H.A[k]=H.A[parent(k)]
K=parent[k]
H.A.[k]=el
}

The heapDequeue algorithm dequeues an item from max-heap. Just like the
heapEnqueue it also call another algorithm called hepifyDown. Below is the
heapDequeue algorithm:

Integer heapDequeue(H: a max-heap)

94
If (H.heapSize=0)
Then return -999
max=H.A[1]
H.A[1]=H.A[H.heapSize]
H.heapSize=H.heapSize-1
heapifyDown(H,1)
return max
}

heapifyDown Alogorithm:

void heapifyDown(H: a max-heap; k:integer){


l=left(k)
r=right(k)
if (I< H.heapSize) and (H.A[I]>H.A[k])
then largest=l
else largest=k
if(((r<H.heapSize) and (H.A[r]>H.A[largest]))
then largest =r
if (largest ≠ k) then
swap H.A[k] with H.A[largest]
heapifyDown(H,largest)
}

95
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 8.2: Programming Activity


1. Implement the max-heap using the programming language of your choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

96
C. Heaps for Sorting
At the end of this topic the student is expected to:
 Design algorithm to sort a keys using heapsort
 Explain the heapsort algorithm

Sorting a key can also be efficiently represented by heaps. Below is the heapSort
algorithm:

void heapSort (H: almost complete binary tree; n:integer)


H.heapSize=n
For j=n/2 downto 1
heapifyDown(j)
for j=n down to 2
swap H.A[1] =H.heapSize-1;
H.heapSize=n;
}

The above algorithm sort the keys ascending order. On line number 2 to 4 the
heapsort build first the max-heap of size n. Lines 5-8, the keys in the max-heap are
then sorted.

97
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 8.3: Illustration


Illustrate how the heaps sorting. The keys to be sorted are depends on you.

98
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercises 8.3a: Programming Activity


1. Implement the heaps sort algorithm using the programming language of your
choice.

Note: Attach the screenshots of the output and the codes as evidence.

Assessment:

Criteria Perfect Score Score


Program Correctness
Ability to formulate code
and algorithms that reliably 50
produces correct answers or
appropriate results.
Syntax
Ability to understand and
30
follow the rules of the
programming language.
Logic
Ability to specify
conditions, control flow, and
20
data structure that are
appropriate for the problem
domain.
Total
100

99
References:

Delfinado, Cecil Jose. Data Structures and Algorithms. C & E Publishing, Inc. 2016
Joyce Avestro. (2006). Data Structure. Philippine Society of IT Educators Convention.
https://www.tutorialspoint.com/data_structures_algorithms/index.htm

100
CHAPTER 9: GRAPHS

Objectives: At the end of this Chapter, the student should be able to:
1. Differentiate undirected and directed graph
2. Illustrate terms associated with graphs

A. Graph ADT Specification


At the end of this topic the student is expected to:
 Define Graph
 List and explain the two types of graph
 Define subgraph and path

The element of finite set is generally modelled by the graph. A graph G=(V,E) is
a finite set V of vertices or nodes and a set E of edges or arcs.

Figure 9.0 Example of a Graph

In the above graph,


V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}
A graph can directed or undirected. An undirected graph is a graph in which the
pair of vertices representing an edge is unordered, i.e.,( i,j) and (j,i) represent the same
edge.

Figure 9.1 Example of an undirected graph

Two vertices i and j are adjacent if (i, j) is an edge in E. The edge (i, j) is said to
be incident on vertices i and j.

101
Figure 9.2 Edge (i,j)

A complete undirected graph is a graph in which an edge connects every pair of


vertices. If a complete undirected graph has n vertices, there are n(n -1)/2 edges in it.

Figure 9.3 Complete undirected graph

A directed graph or digraph is a graph in which each edge is represented by an


ordered pair <i, j>, here i is the head and j is the tail of the edge. The edges <i,j> and<j,i>
are two distinct edges.

Figure 9.4 Directed graph

A complete directed graph is a graph in which every pair of vertices i and j are
connected by two edges<i,j> and <j,i>. There are n(n-1) edges in it.

102
Figure 9.5 Complete directed graph

A subgraph of an undirected (directed) graph G = (V,E) is an undirected


(directed) graph G‟ = (V‟,E‟)such that V  V and E‟  E.

Figure 9.6 Example of subgraph

A path from vertex u to vertex w in an undirected [directed] graph G = (V,E) is a


sequence of vertices vo, v1, v2, ..., vm-1, vm where vo m
(v0,v1),(v1,v2),..., (vm-1, vm) [ <v0,v1>, <v1,v2>, ...,<vm-1, vm>] are edges in E.

The length of a path refers to the number of edges in it. A simple path is a path
in which all vertices are distinct, except possibly the first and the last. A simple path is a
simple cycle if it has the same start and end vertex.

103
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms

Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________

Exercise 9.1: Illustration


Use the alphabet of your name as keys. Draw an undirected and directed graph on the
space provided.

104
References:

Delfinado, Cecil Jose. Data Structures and Algorithms. C & E Publishing, Inc. 2016
Joyce Avestro. (2006). Data Structure. Philippine Society of IT Educators Convention.
https://www.tutorialspoint.com/data_structures_algorithms/index.htm

105

You might also like