Data Structure and Algorithms Module
Data Structure and Algorithms Module
TABLE OF CONTENTS
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
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:_______________________
5
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________
6
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________
7
B. Data Structure
8
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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:______________________
11
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
12
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________
13
D. Recursion
At the end of this topic the student is expected to:
Explain recursion
Explain how chain forms
Write an recursive algorithm
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.
14
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________
15
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_________________________________________________ Date:____________
S.Y./Semester:_______________________ Course and Year:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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.
18
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:_____________
S.Y./Semester:_______________________ Course and Year:______________________
19
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:_____________
S.Y./Semester:_______________________ Course and Year:______________________
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:______________________
22
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
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:______________________
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:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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
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
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:______________________
3. Discuss the Binary Search and write the algorithm of Binary search.
29
4. Discuss the bubble 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:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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
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:______________________
1. Give a real life example of stacks. Which stack operations do these example
supports exactly?
35
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
5.push(s,„D‟) 6.pop(s)
7.push(s,„E‟) 8.push(s,„f‟)
36
B. Stack ADT Representation and Implementation
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:
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:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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
+67
*8+67
67+
867 + *
40
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
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:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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.
44
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
45
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
46
7. enqueue (q,„E‟) 8. enqueue (q,„f‟)
47
B. Queues ADT Representation and Implementation
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. }
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:
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:______________________
50
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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.
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.
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:______________________
54
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
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
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
Slist=record {
head,tail; snode pointers;
}
The following are the psuedo code for singly linked list operation:
New operation:
isEmpty:
toString:
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:
addtoTail:
deleteFromHead:
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:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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:
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:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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.
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:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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
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.
66
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
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
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.
68
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
2. The number of leaves and internal vertices of a full binary with 1,000 edges
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.
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:______________________
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:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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
73
Figure 6.6 Inorder Traversal
Postorder traversal, a node is visited after both its subtrees have been explored.
74
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
Inorder Sequence:
Preorder Sequence:
Postorder Sequence:
2.
Inorder Sequence:
75
Preorder Sequence:
Postorder Sequence:
3.
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:______________________
77
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
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
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.
80
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
81
B. Binary Search Tree – Search operation
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:
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:______________________
83
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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:______________________
86
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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:______________________
89
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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.
92
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
93
B. Heaps for Priority Queues
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]
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:
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:
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:
95
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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:
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:______________________
98
COLEGIO de KIDAPAWAN
Information Technology Education Department
Data Structures and Algorithms
Name:_______________________________________________ Date:______________
S.Y./Semester:_______________________ Course and Year:______________________
Note: Attach the screenshots of the output and the codes as evidence.
Assessment:
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
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.
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 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
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:______________________
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