Ok CMPE 30052 DATA STRUCTURES AND ALGORITHM 1
Ok CMPE 30052 DATA STRUCTURES AND ALGORITHM 1
COMPILED BY:
ENGR.
CMPE-30052 JULIUS S. CANSINO ENGR. JULIAN L. LORICO
Page 1 ofJR.
90
ENGR. PEDRITO M. TENERIFE JR.
TABLE OF CONTENTS
CMPE-30052 Page 2 of 90
MODULE 1: INTRODUCTION TO DATA STRUCTURES, SEARCHING
AND SORTING
Overview:
Data Structures are the programmatic way of storing data so that data can be used efficiently. Almost
every enterprise application uses various types of data structures in one or the other way. This tutorial
will give you a great understanding on Data Structures needed to understand the complexity of enterprise
level applications and need of algorithms, and data structures
(https://www.tutorialspoint.com/data_structures_algorithms/index.htm).
Module Objectives:
After successful completion of this module, you should be able to:
• understand the basics of data structure
• learn the various sorting algorithms
• explore how to implement the different sorting algorithm
• discover how the sorting algorithms perform
A data structure should be seen as a logical concept that must address two fundamental
concerns. First, how the data will be stored, and Second, what operations will be performed on it.
As data structure is a scheme for data organization so the functional definition of a data structure
should be independent of its implementation. The functional definition of a data structure is known as
ADT (Abstract Data Type) which is independent of implementation. The way in which the data is
organized affects the performance of a program for different tasks. Computer programmers decide
which data structures to use based on the nature of the data and the processes that need to be
performed on that data. Some of the more commonly used data structures include lists, arrays, stacks,
queues, heaps, trees, and graphs.
CMPE-30052 Page 3 of 90
CLASSIFICATION OF DATA STRUCTURES
Data structures can be classified as Simple, Compound, Linear and Non- Linear Data Structure
CMPE-30052 Page 4 of 90
OPERATIONS APPLIED ON NON-LINEAR DATA STRUCTURES:
The following list of operations applied on non-linear data structures.
1. Add elements
2. Delete elements
3. Display the elements
4. Sort the list of elements
5. Search for a data element
For example: Tree, Decision tree, Graph and Forest
ALGORITHMS
STRUCTURE AND PROPERTIES OF ALGORITHM
An Algorithm has the following structure:
1. Input Step
2. Assignment Step
3. Decision Step
4. Repetitive Step
5. Output Step
An Algorithm has the following properties:
1. Finiteness: An algorithm must terminate after a finite number of steps.
2. Definiteness: The steps of the algorithm must be precisely defined or unambiguously specified.
3. Generality: An algorithm must be generic enough to solve all problems of a particular class.
4. Effectiveness: the operations of the algorithm must be basic enough to be put down on pencil
and paper. They should not be too complex to warrant writing another algorithm for the operation.
5. Input-Output: The algorithm must have certain initial and precise inputs, and outputs that may
be generated both at its intermediate and final steps.
CMPE-30052 Page 5 of 90
SEARCHING TECHNIQUES
LINEAR SEARCH: Searching is a process of finding a
particular data item from a collection of data items based on
specific criteria. Every day we perform web searches to locate
data items containing in various pages. A search typically
performed using a search key and it answers either True or
False based on the item is present or not in the list. Linear
search algorithm is the simplest algorithm to do sequential
search and this technique iterates over the sequence and
checks one item at a time, until the desired item is found or all
items have been examined. In Python the in operator is used to find the desired item in a sequence of
items. The in operator makes searching task simpler and hides the inner working details.
Consider an unsorted single dimensional array of integers and we need to check whether 31 is present
in the array or not, then search begins with the first element. As the first element doesn't contain the
desired value, then the next element is compared to value 31 and this process continues until the desired
element is found in the sixth position. Similarly, if we want to search for 8 in the same array, then the
search begins in the same manner, starting with the first element until the desired element is found. In
linear search, we cannot determine that a given search value is present in the sequence or not until the
entire array is traversed.
BINARY SEARCH
In Binary search algorithm, the target key is examined in a sorted sequence and this algorithm starts
searching with the middle item of the sorted sequence.
a. If the middle item is the target value, then the search item is found and it returns True.
b. If the target item < middle item, then search for the target value in the first half of the list.
c. If the target item > middle item, then search for the target value in the second half of the list.
CMPE-30052 Page 6 of 90
SORTING TECHNIQUES
Sorting in general refers to various methods of arranging or ordering things based on criteria's (numerical,
chronological, alphabetical, hierarchical etc.). There are many approaches to sorting data and each has
its own merits and demerits.
BUBBLE SORT
This sorting technique is also known as exchange sort, which arranges values by iterating over the list
several times and in each iteration the larger value gets bubble up to the end of the list. This algorithm
uses multiple passes and in each pass the first and second data items are compared. if the first data item
is bigger than the second, then the two items are swapped. Next the items in second and third position
are compared and if the first one is larger than the second, then they are swapped, otherwise no change
in their order. This process continues for each successive pair of data items until all items are sorted.
BUBBLE SORT ALGORITHM
Step 1: Repeat Steps 2 and 3 for i=1 to 10
Step 2: Set j=1
Step 3: Repeat while j<=n
(A) if a[i] < a[j]
Then interchange a[i] and a[j]
[End of if]
(B) Set j = j+1 [End of Inner loop]
[End of Step 1 Outer Loop]
Step 4: Exit
SELECTION SORT
Selection sort algorithm is one of the simplest
sorting algorithm, which sorts the elements in
an array by finding the minimum element in
each pass from unsorted part and keeps it in
the beginning. This sorting technique
improves over bubble sort by making only
one exchange in each pass. This sorting
technique maintains two sub arrays, one sub
array which is already sorted and the other
one which is unsorted. In each iteration the
minimum element (ascending order) is
picked from unsorted array and moved to
sorted sub array. Selection Sort Algorithm
is shown on the right
CMPE-30052 Page 7 of 90
INSERTION SORT
An algorithm considers the elements one at a time,
inserting each in its suitable place among those
already considered (keeping them sorted). Insertion
sort is an example of an incremental algorithm. It
builds the sorted sequence one number at a time.
Example of insertion sort is shown at the right
QUICK SORT
Quick sort is a divide and conquer algorithm. Quick sort first divides a large list into two smaller sub-lists:
the low elements and the high elements. Quick sort can then recursively sort the sub-lists. The steps are:
The base case of the recursion is lists of size zero or one, which never need to be sorted.
MERGE SORT
Merge sort is based on Divide and conquer method. It takes the list to be sorted and divide it in half to
create two unsorted lists. The two unsorted lists are then sorted and merged to get a sorted list. The
two unsorted lists are sorted by continually calling the merge-sort algorithm; we eventually get a list of
size 1 which is already sorted. The two lists of size 1 are then merged.
MERGE SORT PROCEDURE
This is a divide and conquer algorithm.
This works as follows:
1. Divide the input which we have to sort into two parts in the middle. Call it the left part and right
part.
2. Sort each of them separately. Note that here sort does not mean to sort it using some other
method. We use the same function recursively.
3. Then merge the two sorted parts.
Input the total number of elements that are there in an array (number_of_elements). Input the array
(array[number_of_elements]). Then call the function MergeSort() to sort the input array. MergeSort()
function sorts the array in the range [left,right] i.e. from index left to index right inclusive. Merge () function
merges the two sorted parts. Sorted parts will be from [left, mid] and [mid+1, right]. After merging output,
the sorted array.
CMPE-30052 Page 8 of 90
Watch:
1. https://www.youtube.com/watch?v=xOuRE3IuEB8
2. https://www.youtube.com/watch?v=xLetJpcjHS0
Read:
1. https://www.studytonight.com/data-structures/introduction-to-data-structures
2. https://www.youtube.com/watch?v=JeznW_7DlB0
3. www.coelms.com
Review:
1. https://www.javatpoint.com/data-structure-tutorial
2.https://www.bing.com/videos/search?q=video+on+data+structure&ru=%2fvideos%2fsearch%3fq%3d
video%2bon%2bdata%2bstructure%26qpvt%3dvideo%2bon%2bdata%2bstructure%26FORM%3dVDR
E&view=detail&mid=D05312119A41DA386396D05312119A41DA386396&&FORM=VDRVRV
Activities/Assessments:
An organization contains a membership file in which each record contains the following data
for a given member: Name, Address, Telephone Number, Age, Sex.
CMPE-30052 Page 9 of 90
LABORATORY EXERCISE 1
PROBLEM #01
Create a program that will ask the user to enter 10 numbers and display it in ascending order.
PROBLEM #02
Create a program that will convert a decimal number (positive value) to its equivalent binary number.
• Use array for binary values
PROBLEM #03
Create a program that will ask the user to enter 10 numbers and display the 1st and 2nd to
highest number and 1st and 2nd to the lowest number.
• Don’t use array sorting
EXAMPLE PROGRAM OUTPUT:
CMPE-30052 Page 10 of 90
B. One Dimensional Array: Array of Characters
PROBLEM #04
Create a program that will check if a given word is a palindrome or not a palindrome.
CMPE-30052 Page 11 of 90
CMPE 30052 DATA STRUCTURE AND ALGORITHM
QUIZ No. 1
Name:______________________ Date:___________
Student No.:_________________ Score:__________
1. Selection Sort
Answer:
2. Insertion Sort
Answer:
3. Bubble Sort
Answer:
4. Quick Sort
Answer:
5. Merge Sort
Answer:
CMPE-30052 Page 12 of 90
II. Application. Sort the following given value: 5,2,9,4,6 using the ff:
1. Insertion Sort 3. Bubble Sort
CMPE-30052 Page 13 of 90
MODULE 2: LINEAR DATA STRUCTURES
Overview:
Stack is a linear data structure which follows a particular order in which the operations are performed.
The order may be LIFO (Last In First Out) or FILO (First In Last Out).
Module Objectives:
After successful completion of this module, you should be able to:
• learn about stacks
• examine various stack operations
• learn how to implement a stack as an array and linked list
• discover stack applications
CMPE-30052 Page 14 of 90
OPERATIONS OF STACK
There are two operations applied on stack they are the Push and the Pop. While performing Push &
Pop operations the following test must be conducted on the stack. First, Stack is empty or not. Second,
Stack is Full or not.
PUSH
Push operation is used to add new elements in to the stack. At the time of addition first check the stack
is full or not. If the stack is full it generates an error message "stack overflow".
POP
Pop operation is used to delete elements from the stack. At the time of deletion first check the stack
is empty or not. If the stack is empty it generates an error message "stack underflow".
When an element is taken off from the stack, the operation is performed by pop().
STACK is a linear data structure which works under the principle of last in first out operations: push,
pop, display.
1. PUSH: if (top==MAX), display Stack overflow else reading the data and making stack [top]
=data and incrementing the top value by doing top++.
2. POP: if (top==0), display Stack underflow else printing the element at the top of the stack and
decrementing the top value by doing the top.
CMPE-30052 Page 15 of 90
3. DISPLAY: If (top==0), display Stack is empty else printing the
elements in the stack from stack [0] to stack [top].
STACK APPLICATIONS
1. Stack is used by compilers to check for balancing of parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into postfix/prefix form.
4. In recursion, all intermediate arguments and return values are stored on the processor‟s stack.
5. During a function call the return address and arguments are pushed onto a stack and on return
they are popped off.
6. Depth first search uses a stack data structure to find an element from a graph.
PRACTICE EXERCISES: Convert the following infix expression A + B * C – D / E * H into its equivalent
postfix expression.
A A
+ A +
B AB +
* AB +*
CMPE-30052 Page 16 of 90
C ABC -
- ABC*+ -
D ABC*+D -
/ ABC*+D -/
E ABC*+DE -/
* ABC*+DE/ -*
6 6
5 6, 5
2 6,5,2
CMPE-30052 Page 17 of 90
+ 45 3 48 6, 48 Next, „+‟ pops 3 and 45 and
pushes 45 + 3 = 48 is pushed
QUEUE EMPTY
FRONT = REAR = 0 F R
FRONT = 0
REAR = REAR + 1
REAR = 1 F R
FRONT = 0
REAR= REAR +1
REAR = 2 F R
CMPE-30052 Page 18 of 90
Again, insert another element 33 to the queue. The status of the queue 11 22 33
is:
∴FRONT = 0
REAR=REAR + 1 F R
∴REAR = 3
Now, delete an element. The element deleted is the element at the front 22 33
of the queue. So the status of the queue is:
∴REAR = 3
FRONT = FRONT + 1
∴ FRONT = 1 F R
Now, insert new elements 44 and 55 into the queue. The queue status 33 44 55
is:
∴REAR = 5
∴FRONT = 2
F R
CMPE-30052 Page 19 of 90
∴REAR = 4
∴FRONT = 0
This difficulty can overcome if we treat queue position with index 0 as a position that comes after position
with index 4 i.e., we treat the queue as a circular queue.
The various queue operations to perform creation, deletion and display the elements in a queue are as
follows:
1. insertQ(): inserts an element at the end of queue Q.
2. deleteQ(): deletes the first element of Q.
3. displayQ(): displays the elements in the queue.
Linked List Implementation of Queue: We can represent a queue as a linked list. In a queue data is
deleted from the front end and inserted at the rear end. We can perform similar operations on the two
ends of a list. We use two pointers front and rear for our linked queue implementation.
APPLICATIONS OF QUEUES
1. It is used to schedule the jobs to be processed by the CPU.
2. When multiple users send print jobs to a printer, each printing job is kept in the printing queue.
Then the printer prints those jobs according to first in first out (FIFO) basis.
3. Breadth first search uses a queue data structure to find an element from a graph.
CMPE-30052 Page 20 of 90
The DEQUE is represented as follows.
The output restricted DEQUE allows deletions from only one end and input restricted DEQUE allow
insertions at only one end. The DEQUE can be constructed in two ways they are using arrays and using
linked list.
OPERATIONS IN DEQUE
1. Insert element at back
2. Insert element at front
3. Remove element at front
4. Remove element at back
CMPE-30052 Page 21 of 90
Watch:
1. https://www.youtube.com/watch?v=a_agPzERnKI
Read:
1. https://www.studytonight.com/data-structures/introduction-to-data-structures
2. www.coelms.com
Review:
1. https://www.javatpoint.com/data-structure-tutorial
Activities/Assessments:
I. Consider the following stack of characters, where STACK is allocated N=8 memory cells:
STACK: A, C, D, F, K, ___, ___, ___
(For notational convenience, we use “___” to denote an empty memory cell). Draw the STACK as the
following operations take place:
CMPE-30052 Page 22 of 90
LABORATORY EXERCISE 2
CMPE-30052 Page 23 of 90
B. User Defined Function: Return Value
PROBLEM #02
Create a program compute the area of the following polygons and circle.
• Area of square given the side.
• Area of rectangle given the length and width.
• Area of triangle given the base and height.
• Area of circle given the radius.
CMPE-30052 Page 24 of 90
C. Call by Value and Call by Reference
PROBLEM #03
Create a program that will compute the factorial of a given number.
• Use function to pass the value of the number input and to pass the reference of the factorial
value of the number.
PROBLEM #4
Create a simple arithmetic calculator that will add, subtract, multiply and divide two integer
numbers.
• Use function to accept inputs for the two operands.
CMPE-30052 Page 25 of 90
EXAMPLE PROGRAM OUTPUT:
PROBLEM #5
Create a program that will overload a function named linechar that display a line of characters.
Use the given main function below:
int main()
{
linechar();
linechar('@');
linechar(10);
linechar('#',15);
system("pause>0");
return 0;
}
CMPE-30052 Page 26 of 90
D. Pass by Array
PROBLEM #6
Create a program that will ask the user to enter ten numbers and get the sum of all odd
numbers.
• The numbers will be stored in array
• The array value will be pass as argument to the function
CMPE-30052 Page 27 of 90
PROBLEM 8
Create a program that will overload a function named substring. The function will ask the user to
enter the index range of the substring inclusive. Using the function defined the program will display the
whole string value, the substring given the start index, and the substring given the start and last index.
CMPE-30052 Page 28 of 90
CMPE 30052 DATA STRUCTURE AND ALGORITHM
QUIZ No. 1
Name:______________________ Score:___________________
Student No.:_________________ Course/Year:______________
II. Conversion. Given the following infix expression, perform the following conversion.
(2 points
each)
CMPE-30052 Page 29 of 90
III. Application. Given the expression, A+B-C*D/E, get the postfix expression using
stack implementation. (10 points)
CMPE-30052 Page 30 of 90
MODULE 3: LINKED LIST
Overview:
A linked list is a linear data structure, in which the elements are not stored at contiguous memory
locations. The elements in a linked list are linked using pointers. It consists of nodes where each node
contains a data field and a reference(link) to the next node in the list.
Module Objectives:
After successful completion of this module, you should be able to:
• learn about linked lists
• become aware of the basic properties of linked lists
• explore the insertion and deletion operations on linked lists
• discover how to build and manipulate a linked list
Linked lists and arrays are similar since they both store collections of data. Array is the most common
data structure used to store collections of elements. Arrays are convenient to declare and provide the
easy syntax to access any element by its index number. Once the array is set up, access to any
element is convenient and fast.
DISADVANTAGES OF ARRAYS
• The size of the array is fixed. Most often this size is specified at compile time. This makes the
programmers to allocate arrays, which seems "large enough" than required.
• Inserting new elements at the front is potentially expensive because existing elements need to
be shifted over to make room.
• Deleting an element from an array is not possible. Linked lists have their own strengths and
weaknesses, but they happen to be strong where arrays are weak.
• Generally, arrays allocate the memory for all its elements in one block whereas linked lists use
an entirely different strategy. Linked lists allocate memory for each element separately and only
when necessary.
CMPE-30052 Page 31 of 90
DISADVANTAGES OF LINKED LISTS:
• It consumes more space because every node requires a additional pointer to store address of
the next node.
• Searching a particular element in list is difficult and also time consuming.
• A single linked list is one in which all nodes are linked together in some sequential manner.
Hence, it is also called as linear linked list.
• A double linked list is one in which all nodes are linked together by multiple links which helps
in accessing both the successor node (next node) and predecessor node (previous node) from
any arbitrary node within the list. Therefore, each node in a double linked list has two link fields
(pointers) to point to the left node (previous) and the right node (next). This helps to traverse in
forward direction and backward direction.
• A circular linked list is one, which has no beginning and no end. A single linked list can be
made a circular linked list by simply storing address of the very first node in the link field of the
last node.
• A circular double linked list is one, which has both the successor pointer and predecessor
pointer in the circular manner.
CMPE-30052 Page 32 of 90
APPLICATIONS OF LINKED LIST
• Linked lists are used to represent and manipulate polynomial. Polynomials are expression
containing terms with non- zero coefficient and exponents. For example: P(x) = a0 Xn + a1 Xn - 1
+ …… + an-1 X + an
• Represent very large numbers and operations of the large number such as addition,
multiplication and division.
• Linked lists are to implement stack, queue, trees and graphs. 4. Implement the symbol table in
compiler construction.
CMPE-30052 Page 33 of 90
The beginning of the linked list is stored in a "start" pointer which points to the first node. The first node
contains a pointer to the second node. The second node contains a pointer to the third node, ... and so
on. The last node in the list has its next field set to NULL to mark the end of the list. Code can access
any node in the list by starting at the start and following the next pointers.
The start pointer is an ordinary local pointer variable, so it is drawn separately on the left top to show that
it is in the stack. The list nodes are drawn on the right to show that they are allocated in the heap.
The basic operations in a single linked list are
• Creation
• Insertion
• Deletion
• Traversing
INSERTION OF A NODE
One of the most primitive operations that can be done in a singly linked list is the insertion of a node.
Memory is to be allocated for the new node (in a similar way that is done while creating a list) before
reading the data. The new node will contain empty data field and empty next field. The data field of the
CMPE-30052 Page 34 of 90
new node is then stored with the information read from the user. The next field of the new node is
assigned to NULL. The new node can then be inserted at three different places namely:
• Inserting a node at the beginning
• Inserting a node into the single linked list at a specified intermediate position other than
beginning and end.
CMPE-30052 Page 35 of 90
DELETION OF A NODE
Another primitive operation that can be done in a singly linked list is the deletion of a node. Memory is to
be released for the node to be deleted. A node can be deleted from the list from three different places
namely.
• Deleting a node at the beginning.
CMPE-30052 Page 36 of 90
Note that if your linked lists do include a header node, there is no need for the special case code given
above for the remove operation; node n can never be the first node in the list, so there is no need to
check for that case. Similarly, having a header node can simplify the code that adds a node before a
given node n.
Note that if you do decide to use a header node, you must remember to initialize an empty list to contain
one (dummy) node, you must remember not to include the header node in the count of "real" nodes in
the list.
It is also useful when information other than that found in each node of the list is needed. For example,
imagine an application in which the number of items in a list is often calculated. In a standard linked list,
the list function to count the number of nodes has to traverse the entire list every time. However, if the
current length is maintained in a header node, that information can be obtained very quickly. maximum
size of a list a head of time, you can pre-allocate the nodes in a single array. The result is a hybrid
structure – an array based linked list.
An example of null terminated single linked list where all the nodes are allocated contiguously in
an array.
CMPE-30052 Page 37 of 90
Watch:
1. https://www.youtube.com/watch?v=JlMyYuY1aXU
Read:
1. https://www.coelms.com
Review:
1. https://www.studytonight.com/data-structures/introduction-to-data-structures
Activities/Assessments:
Given below is a list of five hospital patients and their room numbers. (10 points)
A. Fill in values for NSTART and NLINK so that they form an alphabetical listing of the names(Ascending).
B. Fill in values for RSTART and RLINK so that they form an ordering of the room numbers.(Descending)
NSTART
NAME ROOM NLINK RLINK
1 Brown 650
2 Smith 422
CMPE-30052 Page 38 of 90
LABORATORY EXERCISE 3
PROBLEM #1
Convert the predefined function strcmp() to user defined function.
Note: strcmp() returns three values based on the lexicographical order of the characters based on the
ASCII table
PROBLEM #2
Convert the predefined function strcpy() to user defined function.
PROBLEM #3
Convert the predefined function strcat() to user defined function.
CMPE-30052 Page 39 of 90
PROBLEM #4
Convert a program that will determine if the given word input is a palindrome. The program will trim the
trailing spaces of the given word.
HINT: Create a user defined function for getting the length of the string and a string trim function for eliminating
trailing white spaces.
CMPE-30052 Page 40 of 90
CMPE 30052 DATA STRUCTURES and ALGORITHM
MIDTERM EXAMINATION
Name Section Score
TEST I. MULTIPLE CHOICE. Choose the letter corresponding to the best choice. Use the answer sheet that has been
attached to this questionnaire. To register your answer, shade the appropriate oval/circle corresponding to each
number. Choose option “E” if in any case there’s no correct answer given on the selection set .
1. The set of native data types that a particular computer can support is determined by :
(a) type of hardware company
(b) what functions have been wired into hardware
(c) what software support is required
(d) None of these.
2. While considering data structure implementation, the factor(s) under consideration is (are) :
(a) time (b) time and space
(c) time, space and processor (d) None of these.
CMPE-30052 Page 41 of 90
(a) The separation of the representation of data from the applications that use the data at a logical
level
(b) The logical picture of a data type, plus the specifications of the operations required to create and
manipulate objects of this data type
(c) A collection of data elements whose organization is characterized by accessing operations that are
used to store and retrieve the individual data elements
(d) None of these.
8. What will happen if a function is executed and the precondition for the function is not met?
a. An error message will be printed. b. The program will loop indefinitely.
b. The system will crash. d. Any of the above results could happen
9. If the precondition fails, it is a good idea to write a useful error message and then halt the
program. Why is the program halted?
a. Most operating systems forbid continuation.
b. The function is no longer guaranteed to make the postcondition true.
c. The function's memory requires have become exponential (or worse).
d. The function's running time has become exponential (or worse).
CMPE-30052 Page 42 of 90
15. Three algorithms do the same task. Algorithm 1 is O(N2), Algorithm 2 is O(N), and Algorithm 3 is
O(Log2 N). Which algorithm should execute the fastest for large values of N?
(a) O(N) (b)O(N) (c)O(log2 N) (d) None of these.
16. Which of the following algorithm should execute the slowest for large values of N?
(a) O(N) (b) O(N2) (c) O(log2 N) (d) None of these.
17. What should never be found in the top level of a top-down design?
(a) Details (b) Coding (c) Decisions (d) None of these
19. Which of the following formulas in big-O notation best represent the expression n²+35n+6?
a. O(n³) b. O(n²) c. O(n) d. O(42)
(a) (i) and (iv) only (b) (i), (ii) and (iii) only
(c) (i) only (d) (iv) only
CMPE-30052 Page 43 of 90
26. Which of the following statements is correct in connection with stacks?
(a) Return and remove the most recently inserted item from the stack, if stack is not empty.
(b) Insert a new item to the top of the stack, if stack is full.
(c) Elements can be deleted from both ends.
(d) Return and remove the least recently inserted item from the stack, if stack is not empty.
27. Which of the following is a / are possible operation(s) in connection with stacks?
(a) Reverse the order of elements on stack S using two additional stacks.
(b) Reverse the order of elements on stack S using additional variables.
(c) Reverse the order of elements on stack S using one stack and some additional queues.
(d) Sort the elements of stacks using one additional stack.
32. Convert the following infix expression to post fix notation Z – (((X + I) * 2) - 5)/Y
(a) Z X I + * 2 5 – / Y (b) Z X – I + 2 * 5 – Y I -
(c) Z X I + 2 * 5 – Y / - (d) Z X I + 2 5 * - Y /-.
33. A data structure in which an element is added and removed only from one end. is known
(a) queue (b) stack
(c) in-built data structure (d) None of these
34. “Get a node, store new element and insert the new node at the top" refers to insert operation in non-
empty
(a) stack (b) array (c) queue (d) None of these.
35. A data structure in which elements are added or removed only at a fixed end is known as
(a) queue (b) array (c) stack (d) Linked List.
37. The integers 1, 2, 3, 4 are pushed into the stack in that order. They may be popped out of the stack
in any valid order. The integers which are popped out produce a permutation of the numbers 1,2,3,4.
Which of the following permutation can never be produced in such a way?
CMPE-30052 Page 44 of 90
(a) 1,2,3,4. (b) 4,3,2, 1.
(c) 4, 2, 3. 1. (d) 3, 2,4, 1.
38. Which of the following types of expressions do not require precedence rules for evaluation?
(a) Fully parenthesized infix expression (b) Postfix expression
(c) Partially parenthesized infix expression (d) More than one of the above
40. If the sequence of operations - push (1), push (2), pop, push (1) , push (2), pop, pop, pop, push (2),
pop, are performed on a stack, the sequence of popped out values are
(a) 2, 2, 1, 1, 2 (b) 2, 2, 1, 2, 2
(c) 2, 1, 2, 2, 1 (d) 2, 1, 2, 2, 2
41. In evaluating the arithmetic expression 2 * 3 - (4 + 5), using stacks to evaluate its equivalent post-fix
form, which of the following is stack output?
(a) -3 (b) 7
(c) 3 (d) 0
42. Stack A has the entries a, b, c (with a on top). Stack B is empty. An entry popped out of stack A can
be printed immediately or pushed to stack B. An entry popped out of stack B can only be printed. In this
arrangement, which of the following permutations of a, b, c is not possible?
(a) b a c (b) b c a (c) cab (d) a b c
Questions No. 43 and No. 44 are based on the following straight queue which can be allocated
eight integers and five operations.
front = 3 rear= 5
Queue = - , - , 2 , 4 ,5, - , - , -
43. What are the final front and rear values when the above operations are performed into a straight
queue?
CMPE-30052 Page 45 of 90
(a) front = 7 rear=2 (b) front = 2 rear=7 (c) front = 7 rear=8 (d) front = 5 rear=8
44. What are the final front and rear values when the above operations are performed into a circular
queue?
(a) front = 7 rear=3 (b) front = 2 rear=7 (c) front = 2 rear=8 (d) front = 5 rear=8
45. The initial configuration of a queue is a, b, c, d, and a is in the front end. To get the configuration d,
c, b, a,
one needs a minimum of
(a) 2 deletions and 3 additions (b) 3 deletions and 2 additions
(c) 3 deletions and 3 additions (d) 3 deletions and 4 additions
47. The process of accessing data stored in a tape is similar to manipulating data on a
(a) stack (b) queue (c) list (d) heap
49. N elements of a queue are to be reversed using another queue. The number of “ADD” and
“REMOVE”
operations required to do so is
(a) 2*N (b) 4*N (c) N (d) the task can’t be
performed
TEST II.
1. As shown in lecture 02, the structure of the list created by the following code: (2 points)
a_list = [4, 2, 6, 9, 3]
Draw a diagram to show the structure of the list created by the code:
CMPE-30052 Page 46 of 90
2. In our lecture, you were shown diagrams that illustrated how different lists were represented in
memory. Use this approach to draw a diagram showing how the lists labelled e and f are
represented
in memory. (4 points)
a = [1]
b=a
c = [1, 2, 3]
d=c
e = [1, a, c]
f = [2, b, d]
my_list= LinkedList()
for x in[9, 2, 22, 40]:
my_list.add_to_head(x)
my_list.remove_from_tail()
my_list.add_to_tail(32)
my_list.remove_from_head()
my_list.remove_from_head()
my_list.add_to_head(100)
for num in my_list:
print(num, end=" ")
4. The following program uses a Car class to simulate a very simple race between a blue car and
a red car.
(40 points)
blue_car = Car('Blue')
red_car = Car('Red')
print(blue_car, red_car)
blue_car.accelerate(5)
red_car.accelerate(10)
print(blue_car, red_car)
if blue_car.is_faster(red_car):
print('Blue car faster')
else:
print('Blue car not faster')
CMPE-30052 Page 47 of 90
blue_car.accelerate(20)
red_car.accelerate(10)
print(blue_car, red_car)
if blue_car.is_faster(red_car):
print('Blue car faster')
else:
print('Blue car not faster')
class Car:
CMPE-30052 Page 48 of 90
MODULE 4: NON LINEAR DATA STRUCTURES
Overview:
The data structure where data items are not organized sequentially is called non linear data structure.
A data elements of the non linear data structure could be connected to more than one elements to reflect
a special relationship among them. All the data elements in non linear data structure can not be traversed
in single run.
Module Objectives:
After successful completion of this module, you should be able to:
• Learn about binary trees
• Explore various binary tree traversal algorithms
• Learn how to organize data in a binary search tree
• Discover how to insert and delete items in a binary search tree
TREES
A tree is a non-empty set one element of which
is designated the root of the tree while the
remaining elements are partitioned into non-
empty sets each of which is a sub-tree of the
root.
Tree nodes have many useful properties. The depth of a node is the length of the path (or the number
of edges) from the root to that node. The height of a node is the longest path from that node to its leaves.
The height of a tree is the height of the root. A leaf node has no children -- its only path is up to its parent.
BINARY TREE
In a binary tree, each node can
have at most two children. A
binary tree node called the root
together with two binary trees
called the left subtree is either
empty or consists of and the
right subtree.
CMPE-30052 Page 49 of 90
TREE TERMINOLOGIES
LEAF NODE: A node with no children is called a leaf (or external node). A node which is not a leaf is
called an internal node.
PATH: A sequence of nodes n1, n2, . . ., nk, such that ni is the parent of ni + 1 for i = 1, 2,. . ., k - 1. The
length of a path is 1 less than the number of nodes on the path. Thus there is a path of length zero from
a node to itself.
SIBLINGS: The children of the same parent are called siblings.
ANCESTOR AND DESCENDENT: If there is a path from node A to node B, then A is called an
ancestor of B and B is called a descendent of A.
SUBTREE: Any node of a tree, with all of its descendants is
a subtree.
LEVEL: The level of the node refers to its distance from the
root. The root of the tree has level O, and the level of any
other node in the tree is one more than the level of its parent.
The maximum number of nodes at any level is 2n.
HEIGHT: The maximum level in a tree determines its height.
The height of a node in a tree is the length of a longest path
from the node to a leaf. The term depth is also used to denote height of the tree.
DEPTH: The depth of a node is the number of nodes along the path from the root to that node.
ASSIGNING LEVEL NUMBERS AND NUMBERING OF NODES FOR A BINARY TREE: The nodes of
a binary tree can be numbered in a natural way, level by level, left to right. The nodes of a complete
binary tree can be numbered so that the root is assigned the number 1, a left child is assigned twice the
number assigned its parent, and a right child is assigned one more than twice the number assigned its
parent.
CMPE-30052 Page 50 of 90
A full binary tree with height h has 2h + 1 - 1 nodes. A full binary tree of height h is a strictly binary tree all
of whose leaves are at level h.
In the figure shown below the nodes of binary tree are numbered according to the given scheme.
CMPE-30052 Page 51 of 90
The figure shows how a binary tree is represented as an array. The root 3 is the 0 th element while its
leftchild 5 is the 1st element of the array. Node 6 does not have any child so its children i.e. 7th and 8th
element of the array are shown as a Null value.
It is found that if n is the number or index of a node, then its left child occurs at (2n + 1) th position and
right child at (2n + 2)th position of the array. If any node does not have any of its child, then null value is
stored at the corresponding index of the array.
In a linear list nodes are visited from first to last, but a tree being a
nonlinear one we need definite rules. The ways to traverse a tree. All
of them differ only in the order in which they visit the nodes.
CMPE-30052 Page 52 of 90
INORDER TRAVERSAL
To traverse a non-empty tree in inorder the following
steps are followed recursively.
• Visit the Root
• Traverse the left subtree
• Traverse the right subtree
PREORDER TRAVERSAL
Algorithm Pre-order(tree)
1. Visit the root.
2. Traverse the left sub-tree, i.e., call Pre-order(left-sub-tree)
3. Traverse the right sub-tree, i.e., call Pre-order(right-sub-tree)
POST-ORDER TRAVERSAL
Algorithm Post-order(tree)
1. Traverse the left sub-tree, i.e., call Post-order(left-sub-tree)
2. Traverse the right sub-tree, i.e., call Post-order(right-sub-tree)
3. Visit the root.
The above properties of Binary Search Tree provide an ordering among keys so that the operations
like search, minimum and maximum can be done fast. If there is no ordering, then we may have to
compare every key to search a given key.
SEARCHING A KEY
To search a given key in Binary Search Tree, we first compare it with root, if the key is present at root,
we return root. If key is greater than root’s key, we recur for right sub-tree of root node. Otherwise we
recur for left sub-tree.
CMPE-30052 Page 53 of 90
# Key is greater than root's key if root.val < key:
return search(root.right,key)
#Key is smaller than root's key return
search(root.left,key)
Watch:
1. https://www.youtube.com/watch?v=qH6yxkw0u78
Read:
1. https://www.coelms.com
2. https://www.studytonight.com/data-structures/introduction-to-data-structures
Review:
1. https://www.youtube.com/watch?v=qH6yxkw0u78
Activities/Assessments:
Consider the binary search tree. Draw the tree if each of the following operations is applied to the
original tree. (That is, the operations are applied independently, not successively).
A. Node 20 is added to the tree
50
B. Node 15 is added to the tree
C. Node 88 is added to the tree
25 75
D. Node 22 is deleted to the tree
E. Node 25 is deleted to the tree
F. Node 75 is deleted to the tree 22 40 60 90
15 80
30 44
33
CMPE-30052 Page 54 of 90
LABORATORY EXERCISE 4
1. Create a programmer defined function that will do the same as strcpy function.
2. Create a programmers defined function that will do the same as strcmp function.
3. Create a programmers defined function that will do the same as strcat function.
4. Create a programmers defined function that will do the same as strlen function.
CMPE-30052 Page 55 of 90
CMPE 30052 DATA STRUCTURES AND ALGORITHM
QUIZ No. 2
5. Translate this binary expression tree into an infix, prefix, and postfix algebraic expression.
Then solve the numerical answer using any method. Use integer math.
* + 2
4 3 3 *
2 4
Infix: ___________________________________________________________
Prefix: ___________________________________________________________
Postfix: ___________________________________________________________
Answer: __________
CMPE-30052 Page 56 of 90
6. Translate this binary expression tree into an infix, prefix, and postfix algebraic expression.
Then solve the numerical answer using any method. Use integer math.
* 9
3 +
- 6
+ *
2 7 3 8
Infix: ___________________________________________________________
Prefix: ___________________________________________________________
Postfix: ___________________________________________________________
Answer: __________
Now, see if you can follow the same logic and build a BET from these POSTfix expressions:
6 5 – 3 4 + * Evaluate: ____________(int math)
CMPE-30052 Page 57 of 90
CMPE 30052 DATA STRUCTURE AND ALGORTIHM
Quiz No. 3
Name:______________________ Date:_________________
Student No.:_________________ Score:________________
II. Application. Given the values, 5,5,1,9,8,5 create and draw the binary search tree and
answer the following:
CMPE-30052 Page 58 of 90
MODULE 5: GRAPH AND ITS APPLICATIONS
Overview:
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also
referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph.
Module Objectives:
After successful completion of this module, you should be able to:
• describe a graph
• understand how to implement a graph
• describe algorithms to traverse a graph
GRAPH
Graph is a data structure that consists of following two components:
1. A finite set of vertices also called as nodes.
2. A finite set of ordered pair of the form (u, v) called as edge.
The pair is ordered because (u, v) is not same as (v, u) in case of directed graph (di-graph). The pair of
form (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain
weight/value/cost.
The two most commonly used representation of graphs is the Adjacency Matrix and Adjacency List.
There are other representations also like, Incidence Matrix and Incidence List. The choice of the graph
representation is situation specific. It totally depends on the type of operations to be performed and ease
of use.
CMPE-30052 Page 59 of 90
ADJACENCY MATRIX
Adjacency Matrix is a 2D array of size V x V where V is the number of
vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates
that there is an edge from vertex i to vertex j. Adjacency matrix for
undirected graph is always symmetric. Adjacency Matrix is also used to
represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex
i to vertex j with weight w. The adjacency matrix for the above example
graph is shown on the right
Pros: Representation is easier to implement and follow. Removing an edge takes O(1) time. Queries like
whether there is an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done O(1).
Cons: Consumes more space O(V^2). Even if the graph is sparse (contains less number of edges), it
consumes the same space. Adding a vertex is O(V^2) time.
ADJACENCY LIST
An array of linked lists is used. Size of the array is
equal to number of vertices. Let the array be array[
]. An entry array[i] represents the linked list of
vertices adjacent to the ith vertex. This
representation can also be used to represent a
weighted graph. The weights of edges can be
stored in nodes of linked lists. The adjacency list
representation of the above graph is shown on the
right.
CMPE-30052 Page 60 of 90
Algorithm: Breadth-First Search Traversal
BFS(V, E, s)
BREADTH FIRST TRAVERSAL FOR A for each u in V − {s}
GRAPH do color[u] ← WHITE
Breadth First Traversal (or Search) for a graph is d[u] ← infinity
similar to Breadth First Traversal of a tree The only π[u] ← NIL
catch here is, unlike trees, graphs may contain color[s] ← GRAY
cycles, so we may come to the same node again. To
d[s] ← 0
avoid processing a node more than once, we use a
π[s] ← NIL
boolean visited array.
Q←{}
For example, in the following graph, we start ENQUEUE(Q, s)
while Q is non-empty
traversal from vertex 2. When we come to vertex 0,
do u ← DEQUEUE(Q)
we look for all adjacent vertices of it. 2 is also an
adjacent vertex of 0. If we don’t mark visited vertices, for each v adjacent to u
then 2 will be processed again and it will become a do if color[v] ← WHITE
then color[v] ← GRAY
non-terminating process. Breadth First Traversal of
d[v] ← d[u] + 1
the following graph is 2, 0, 3, 1
π[v] ← u
ENQUEUE(Q, v)
DEQUEUE(Q)
color[u] ← BLACK
2. Peer to Peer Networks. In Peer to Peer Networks like Bit Torrent, Breadth First Search is used to find
all neighbor nodes.
3. Crawlers in Search Engines: Crawlers build index using Bread First. The idea is to start from source
page and follow all links from source and keep doing same. Depth First Traversal can also be used for
crawlers, but the advantage with Breadth First Traversal is, depth or levels of built tree can be limited.
4. Social Networking Websites: In social networks, we can find people within a given distance ‘k’ from
a person using Breadth First Search till ‘k’ levels.
5. GPS Navigation systems: Breadth First Search is used to find all neighboring locations.
6. Broadcasting in Network: In networks, a broadcasted packet follows Breadth First Search to reach
all nodes.
7. In Garbage Collection: Breadth First Search is used in copying garbage collection using Cheney’s
algorithm.
CMPE-30052 Page 61 of 90
8. Cycle detection in undirected graph: In undirected graphs, either Breadth First Search or Depth
First Search can be used to detect cycle. In directed graph, only depth first search can be used.
9. Ford–Fulkerson algorithm In Ford-Fulkerson algorithm, we can either use Breadth First or Depth
First Traversal to find the maximum flow. Breadth First Traversal is preferred as it reduces worst case
time complexity to O(VE2).
10. To test if a graph is Bipartite We can either use Breadth First or Depth First Traversal.
11. Path Finding We can either use Breadth First or Depth First Traversal to find if there is a path
between two vertices.
12. Finding all nodes within one connected component: We can either use Breadth First or Depth
First Traversal to find all nodes reachable from a given node.
CMPE-30052 Page 62 of 90
DFS (V, E)
ALGORITHM DEPTH-FIRST SEARCH for each vertex u in V[G]
The DFS forms a depth-first forest comprised of more than do color[u] ← WHITE
one depth-first trees. Each tree is made of edges (u, v) such π[u] ← NIL
that u is gray and v is white when edge (u, v) is explored. The time ← 0
following pseudocode for DFS uses a global timestamp time. for each vertex u in V[G]
do if color[u] ← WHITE
APPLICATIONS OF DEPTH FIRST SEARCH then DFS-Visit(u)
Depth-first search (DFS) is an algorithm (or technique) for
traversing a graph. DFS-Visit(u)
Following are the problems that use DFS as a building block. color[u] ← GRAY
time ← time + 1
1) For an unweighted graph, DFS traversal of the graph d[u] ← time
produces the minimum spanning tree and all pair shortest for each vertex v adjacent to u
path tree.
do if color[v] ← WHITE
2) Detecting cycle in a graph then π[v] ← u
A graph has cycle if and only if we see a back edge during DFS-Visit(v)
DFS. So we can run DFS for the graph and check for back color[u] ← BLACK
edges. (See this for details) time ← time + 1
f[u] ← time
3) Path Finding
We can specialize the DFS algorithm to find a path between
two given vertices u and z.
1. Call DFS (G, u) with u as the start vertex.
2. Use a stack S to keep track of the path between the start vertex and the current vertex.
3. As soon as destination vertex z is encountered, return the path as the
contents of the stack
4) Topological Sorting
DFS search starts from root node then traversal into left child node and continues, if item found it stops
otherwise it continues. The advantage of DFS is it requires less memory compare to Breadth First
Search (BFS).
BFS search starts from root node then traversal into next level of graph or tree and continues, if item
found it stops otherwise it continues. The disadvantage of BFS is it requires more memory compare to
Depth First Search (DFS).
CMPE-30052 Page 63 of 90
Watch:
1. https://www.youtube.com/watch?v=gXgEDyodOJU
Read:
1. https://www.coelms.com
2. https://www.studytonight.com/data-structures/introduction-to-data-structures
Review:
1. https://www.studytonight.com/data-structures/introduction-to-data-structures
Activities/Assessments:
I. Consider the undirected graph given below (20 points)
A. Find all simple path from node A to node H.
B. Adjacency matrix
A B C D
E F G H
CMPE-30052 Page 64 of 90
LABORATORY EXERCISE 5
Problem 1:
Create a program that will ask the user to enter the student record with three quizzes. The program will
display the student record together with the average grade of the three quizzes and display a remark if
the student passed the subject or not. The structure must compose of thee members the id, the name,
and the quiz in array form.
Output:
Case 1: Case 2:
Problem 2:
Create a program that will enter 5 student records with three quizzes. The program will generate an
output that will displays all the student records with their grades and remarks.
grades = average grade of the three quizzes
75 is the passing mark.
CMPE-30052 Page 65 of 90
OUTPUT
Problem 3:
Create a program that will give an output as shown on figure A.The program will ask to input three
customers information. Each customer have three items purchased. Used the given structure below.
Date
day
month
year
CMPE-30052 Page 66 of 90
CMPE-30052 Page 67 of 90
MODULE 6: BINARY TREES AND HASHING
Overview:
Binary Search Tree is a node-based binary tree data structure which has the following properties:
• The left subtree of a node contains only nodes with keys lesser than the node’s key.
• The right subtree of a node contains only nodes with keys greater than the node’s key.
• The left and right subtree each must also be a binary search tree.
Module Objectives:
After successful completion of this module, you should be able to:
• learn about binary search trees
• explore various binary search tree properties and operations
• implement set (ADT) using BST
✓ All keys in n's left subtree are less than the key in n, and
✓ All keys in n's right subtree are greater than the key in n.
In other words, binary search trees are binary trees in which all values in the node’s left subtree are less
than node value all values in the node’s right subtree are greater than node value.
Here are some BSTs in which each node just stores an integer key:
CMPE-30052 Page 68 of 90
In the left one 5 is not greater than 6. In the right
one 6 is not greater than 7. The reason binary-
search trees are important is that the following
operations can be implemented efficiently using
a BST:
▪ insert a key value
▪ determine whether a key value is in the
tree
▪ remove a key value from the tree
▪ print all of the key values in sorted order
Let's illustrate what happens using the following BST and searching for 12:
INSERTING A NODE
A naïve algorithm for inserting a node into a BST is that, we start from the root node, if the node to insert
is less than the root, we go to left child, and otherwise we go to the right child of the root. We continue
this process (each node is a root for some sub tree) until we find a null pointer (or leaf node) where we
cannot go any further. We then insert the node as a left or right child of the leaf node based on node is
less or greater than the leaf node. We note that a new node is always inserted as a leaf node. A recursive
algorithm for inserting a node into a BST is as follows. Assume we insert a node N to tree T. if the tree is
empty, the we return new node N as the tree. Otherwise, the problem of inserting is reduced to inserting
the node N to left of right sub trees of T, depending on N is less or greater than T. A definition is as
follows.
Insert(N, T) = N if T is empty
= insert(N, T.left) if N < T
CMPE-30052 Page 69 of 90
= insert(N, T.right) if N > T
DELETING A NODE
A BST is a connected structure. That is, all nodes in a tree are connected to
some other node. For example, each node has a parent, unless node is the
root. Therefore, deleting a node could affect all sub trees of that node. For
example, deleting node 5 from the tree could result in losing sub trees that are
rooted at 1 and 9.
Hence we need to be careful about deleting nodes from a tree. The best way
to deal with deletion seems to be considering special cases. What if the node
to delete is a leaf node? What if the node is a node with just one child? What
if the node is an internal node (with two children)? The latter case is the hardest
to resolve. But we will find a way to handle this situation as well.
CMPE-30052 Page 70 of 90
CASE 2: The node to delete is a node with one child.
This is also not too bad. If the node to be deleted is a left child of the parent,
then we connect the left pointer of the parent (of the deleted node) to the
single child. Otherwise if the node to be deleted is a right child of the parent,
then we connect the right pointer of the parent (of the deleted node) to single
child.
CMPE-30052 Page 71 of 90
BALANCED SEARCH TREES
A self-balancing (or height-balanced) binary search tree is any node-based binary search tree that
automatically keeps its height (maximal number of levels below the root) small in the face of arbitrary
item insertions and deletions. The red–black tree, which is a type of self-balancing binary search tree,
was called symmetric binary B-tree. Self-balancing binary search trees can be used in a natural way to
construct and maintain ordered lists, such as priority queues. They can also be used for associative
arrays; key-value pairs are simply inserted with an ordering based on the key alone. In this capacity, self-
balancing BSTs have a number of advantages and disadvantages over their main competitor, hash
tables. One advantage of self-balancing BSTs is that they allow fast (indeed, asymptotically optimal)
enumeration of the items in key order, which hash tables do not provide. One disadvantage is that their
lookup algorithms get more complicated when there may be multiple items with the same key. Self-
balancing BSTs have better worst-case lookup performance than hash tables (O(log n) compared to
O(n)), but have worse average-case performance (O(log n) compared to O(1)).
CMPE-30052 Page 72 of 90
Self-balancing BSTs can be used to implement any algorithm that requires mutable ordered lists, to
achieve optimal worst-case asymptotic performance. For example, if binary tree sort is implemented with
a self-balanced BST, we have a very simple-to-describe yet asymptotically optimal O(n log n) sorting
algorithm. Similarly, many algorithms in computational geometry exploit variations on self-balancing
BSTs to solve problems such as the line segment intersection problem and the point location problem
efficiently. (For average-case performance, however, self-balanced BSTs may be less efficient than other
solutions. Binary tree sort, in particular, is likely to be slower than merge sort, quicksort, or heapsort,
because of the tree-balancing overhead as well as cache access patterns.)
Self-balancing BSTs are flexible data structures, in that it's easy to extend them to efficiently record
additional information or perform new operations. For example, one can record the number of nodes in
each subtree having a certain property, allowing one to count the number of nodes in a certain key range
with that property in O(log n) time. These extensions can be used, for example, to optimize database
queries or other list-processing algorithms.
AVL TREES
An AVL tree is another balanced binary search tree. Named after their inventors, Adelson-Velskii and
Landis, they were the first dynamically balanced trees to be proposed. Like red-black trees, they are not
perfectly balanced, but pairs of sub-trees differ in height by at most 1, maintaining an O(logn) search
time. Addition and deletion operations also take O(logn) time.
Balance requirement for an AVL tree: the left and right sub-
trees differ by at most 1 in height.
Yes this is an AVL tree. Examination shows that each left sub-
tree has a height 1 greater than each right sub-tree.
CMPE-30052 Page 73 of 90
No this is not an AVL tree. Sub-tree with root 8 has height 4
and sub-tree with root 18 has height 2.
An AVL tree implements the Map abstract data type just like a regular binary search tree, the only
difference is in how the tree performs. To implement our AVL tree we need to keep track of a balance
factor for each node in the tree. We do this by looking at the heights of the left and right subtrees for
each node. More formally, we define the balance factor for a node as the difference between the height
of the left subtree and the height of the right subtree.
balanceFactor=height(leftSubTree)−height(rightSubTree)
PROPERTIES OF
AVL TREES
AVL trees are identical to standard binary search trees except
that for every node in an AVL tree, the height of the left and right
subtrees can differ by at most 1 (Weiss, 1993, p:108). AVL trees
are HB-k trees (height balanced trees of order k) of order HB-1.
CMPE-30052 Page 74 of 90
red-black trees can be done using only one or two rotations (up to color changes). For this
reason, they (AVL trees) are considered a bit obsolete by some.
To make the processing of m-way trees easier some type of order will be imposed on the keys within
each node, resulting in a multiway search tree of order m (or an m-way search tree). By definition an
m-way search tree is a m-way tree in which:
B TREES
An extension of a multiway search tree of order m is a B-tree of order m. This type of tree will be used
when the data to be accessed/stored is located on secondary storage devices because they allow for
large amounts of data to be stored in a node.
CMPE-30052 Page 75 of 90
A B-tree of order m is a multiway search tree in which:
1. The root has at least two subtrees unless it is the only node in the tree.
2. Each nonroot and each nonleaf node have at most m nonempty children and at least m/2
nonempty children.
3. The number of keys in each nonroot and each nonleaf node is one less than the number of its
nonempty children.
4. All leaves are on the same level.
These restrictions make B-trees always at least half full, have few levels, and remain perfectly balanced.
SEARCHING A B-TREE
An algorithm for finding a key in B-tree is simple. Start at the root and determine which pointer to follow
based on a comparison between the search value and key fields in the root node. Follow the appropriate
pointer to a child node. Examine the key fields in the child node and continue to follow the appropriate
pointers until the search value is found or a leaf node is reached that doesn't contain the desired search
value.
When inserting into a B-tree, a value is inserted directly into a leaf. This leads to three common situations
that can occur:
1. A key is placed into a leaf that still has room.
2. The leaf in which a key is to be placed is full.
3. The root of the B-tree is full.
CMPE-30052 Page 76 of 90
The new leaf is incorporated by moving the middle value to the parent and a pointer to the new leaf is
also added to the parent. This process is continues up the tree until all of the values have "found" a
location.
The new node needs to be incorporated into the tree - this is accomplished by taking the middle value
and inserting it in the parent:
CMPE-30052 Page 77 of 90
Inserting 13 into the following tree:
Results in:
CMPE-30052 Page 78 of 90
There are two main cases to be considered: Deletion from a leaf and Deletion from a Non- Leaf
Results in:
B. If the leaf is less than half full after deleting the desired value (known as underflow), two things
could happen
Deleting 7
from the tree
above results in:
• If there is a left or right sibling with the number of keys exceeding the minimum
requirement, all of the keys from the leaf and sibling will be redistributed between them
by moving the separator key from the parent to the leaf and moving the middle key from
the node and the sibling combined to the parent.
CMPE-30052 Page 79 of 90
Now delete 8 from the tree:
• If the number of keys in the sibling does not exceed the minimum requirement, then the
leaf and sibling are merged by putting the keys from the leaf, the sibling, and the
separator from the parent into the leaf. The sibling node is discarded and the keys in the
parent are moved to "fill the gap". It's possible that this will cause the parent to
underflow. If that is the case, treat the parent as a leaf and continue repeating step 1b-2
until the minimum requirement is met or the root of the tree is reached.
Watch:
1. https://www.youtube.com/watch?v=qH6yxkw0u78
Read:
1. https://www.coelms.com
2. https://www.studytonight.com/data-structures/introduction-to-data-structures
Review:
1. https://www.studytonight.com/data-structures/introduction-to-data-structures
Activities/Assessments:
CMPE-30052 Page 80 of 90
LABORATORY EXERCISE 8
Complete the following code and then generate an equivalent code in python:
CMPE-30052 Page 81 of 90
CMPE-30052 Page 82 of 90
COEN30052 DATA STRUCTURE AND ALGORITHM ANALYSIS
FINAL EAMINATION
Name Date
Section Score
MULTIPLE CHOICE [100pts]. Choose AND ENCIRCLE the letter of the BEST answer.
1 Linked list are
3 Allows insertion at only one end (rear end) but allows deletion at both ends, rear and front ends
on the lists.
a. output restricted b. input restricted c. priority queue d. circular queue
queue queue
4 Place where insertion and deletion takes place in stack.
8 Type of data structures, data values of different types are grouped and stored.
9 Is a homogenous list in which elements can be added or inserted and deleted or removed from
both ends.
a. priority queue b. circular queue c. double ended d. dequeue
queue
10 In stack every pop operation, the top of the stack is.
CMPE-30052 Page 83 of 90
a. enqueue b. dequeue c. pop d. traverse
a. negative one (-1) b. positive one (1) c. zero (0) d. NULL value
20 Stack behavior
21 Allows deletion at only one end (front end) but allows insertion at both ends, rear and front
ends, of the lists.
a. input restricted b. output restricted c. circular queue d. simply queue
queue
22 Process of going through all the nodes from one end to another end of the linked list.
23 The process of inserting an element on one end and deleting an element on the other end
24 Type of data structure where values of the same types of data are stored.
CMPE-30052 Page 84 of 90
a. pointer b. linked list c. non- d. homogeneous
homogeneous
25 Queue behavior
26 A condition occurs if the array is full and no new element can be accommodated.
27 Enables a program to move through the list in one direction, which is usually from the front of
the list moving to the end of the list.
a. doubly linked list b. singly linked list c. circular linked list d. doubly circular
linked list
28 A notation where the operators is written before the operands.
30 Is a collection of items that exhibits the behavior that the last item in is the first item out.
31 Is a data structure that makes it easy to rearrange data without having to move data in
memory.
a. array b. stack array c. linked list d. queue array
a. circular linked list b. singly linked list c. doubly linked list d. queue
35 Stores data and allow various operations on the data to access and change it.
a. data structure b. int data type c. primitive data d. abstract data type
type
Question number 36 to 40 convert the given expression to prefix form
36 A*C/D
CMPE-30052 Page 85 of 90
a. * / A C D b. / * A C D c. / C D * A d. * A / C D
37 A+B^C–D
a. – + A ^ B C D b. ^ – + A B C D c. + A B ^ – C D d. – + ^ A B C D
38 (A+B)*C/D
a. * + A B / C D b. / * + A B C D c. + A B * / C D d. * + / A B C D
39 (A*B)^C–D*F
a. – ^ * A B C * D F b. – * A ^ B C * D F c. * A B ^ – C * D F d. * ^ – A B C * D F
40 A+B–C*D/E^F
a. – + A B / * C D ^ E b. + A B – * C D / ^ E c. + A B – * C / D E d. + A B – / * C D ^ E
F F ^F F
Question number 41 to 45 convert the given expression to postfix form
41 A*B–C
a. A B * C – b. A B C * – c. A B C – * d. A B – C *
42 A+(B–C)^D
a. A B C – D + ^ b. A B C – + D ^ c. A B C – D ^ + d. A B C D + – ^
43 A^B–C/D
a. A B C D ^ – / b. A B C ^ – D / c. A B ^ C D / – d. A B ^ – C D /
44 A/(B*C)+D
a. A B C D / * + b. A B C * / D + c. A B / C * D + d. A B C / * D +
45 A^(B*C)/(D–F)
a. A B C D F ^ * / – b. A B C * ^ / D F – c. A B C * ^ D F / – d. A B C * ^ D F – /
47 The highest number of nodes that is possible in a way starting from first node (ROOT) to a leaf.
CMPE-30052 Page 86 of 90
a. depth b. level c. path d. height
51 In Binary tree, any node that has at least one empty child
52 Stores keys in the nodes in a way so that searching, insertion and deletion can be done
efficiently.
a. struct b. tree data structure c. binary search d. heap
tree
53 It is the mother node of a tree structure.
CMPE-30052 Page 87 of 90
63 A type of binary tree where every non-leaf node is filled with left and right sub-trees
66 A sort algorithm where each element is compared with its adjacent element. If the first element
is larger than the second one, then the positions of the elements are interchanged, otherwise it
is not changed
a. quick sort b. bubble sort c. heap sort d. selection sort
67 A sort algorithm that finds the smallest element of the array and interchanges it with the
element in the first position of the array. Then it finds the second smallest element from the
remaining elements in the array and places it in the second position of the array and so on.
a. selection sort b. quick sort c. bubble sort d. insertion sort
68 Sorting algorithm that sorts a set of values by inserting values into an existing sorted file.
69 Is the process of combining two or more sorted array into a third sorted array.
70 A sorting algorithm that is defined as an almost complete binary tree of n nodes such that the
value of each node is less than or equal to the value of the father.
a. insertion b. selection c. heap d. quick
71 In Binary Search Tree a key value in the left child is more than the value of _____.
CMPE-30052 Page 88 of 90
a. node b. internal node c. root d. leaf
76 In Binary Search Tree a key value in the right child is ____________to the value of root.
79 Refers to the process of visiting each node in a tree data structure, exactly once, in a
systematic way
a. searching b. sorting c. merging d. tree traversal
Figure A
CMPE-30052 Page 89 of 90
85 Parent of e
86 Sibling of k.
a. i b. e c. a d. none
87 descendants of c
89 level of e
90 descendants of j
For number 91 to 100 Given the following value 18, 15, 30, 17, 35, 10, 22, 13, 18, 16, 31, 8, 25, 9, 4
91-94: Draw the equivalent Binary Search Tree
95-96: Write the values using the in order traversal
97-98: Write the values using the pre order traversal
99-100: Write the values using the post order traversal
CMPE-30052 Page 90 of 90