Professional Documents
Culture Documents
DSA LAB Manual Muhammad
DSA LAB Manual Muhammad
DSA LAB Manual Muhammad
Laboratory Manual
For
(CS- 211)
Prepared by:
Guided by:
Approved by:
Designation: Designation:
Department: Department:
SOFTWARE LAB RUBRICS FOR ASSESSING IN-LAB PERFORMANCE
PLO-2 (PROBLEM ANALYSIS)
TABLE OF CONTENT
Blooms
Taxanomy’s
S. No. Lab Objectives
Psychomotor
domain
Identification of various data structures and algorithm and implement
1 P - 01
a matrix addition program.
Show your knowledge of array data structures by coding matrix
2 P – 03
multiplication program.
Perform processing of string data structures using string processing
3 P - 02
functions.
Demonstrate your understanding of linear search by implementing its
4 P - 03
algorithm.
Implement Binary search algorithm and search an element in a sorted
5 P - 02
array.
6 Build a Bubble sort algorithm to sort the elements of an array. P – 02
1
SEMESTER 3
Lab #01
Objective: Identification of various data structures and algorithm and implement a matrix addition
program.
Theory:
Data Structure is defined as the way in which data is organized in the memory location. There are 2
types of data structures:
In linear data structure all the data are stored linearly in the memory. All the data are saved in
continuously memory locations and hence all data elements are saved in one boundary. A linear
data structure is one in which we can reach directly only one element from another while travelling
sequentially. The main advantage, we find the first element, and then it’s easy to find the next data
elements. The disadvantage, the size of the array must be known before allocating the memory.
Array
Stack
Queue
Linked List
Every data item is attached to several other data items in a way that is specific for reflecting
relationships. The data items are not arranged in a sequential structure. The various types of non-linear
data structures are
2
SEMESTER 3
Trees
Graphs
The term data structure is used to describe the way data is stored, and the term algorithm is used to
describe the way data is processed. Data structures and algorithms are interrelated. Choosing a data
structure affects the kind of algorithm you might use, and choosing an algorithm affects the data
structures we use.
In contiguous structures, terms of data are kept together in memory (either RAM or in a file). An array
is an example of a contiguous structure. Since each element in the array is located next to one or two
other elements.
In contrast, items in a non-contiguous structure and scattered in memory, but we link to each other in
some way. A linked list is an example of a non-contiguous data structure. Here, the nodes of the list are
linked together using pointers stored in each node.
3
SEMESTER 3
Array:
Array, which stores a fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a collection of variables of
the same type. Arrays can be single dimensional or multi-dimensional (2 or more).
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
Declaring arrays:
Initializing arrays:
4
SEMESTER 3
Matrix Addition:
Matrix addition is the operation of adding two matrices by adding the corresponding entries together.
Two matrices must have an equal number of rows and columns to be added. The sum of two matrices A
and B will be a matrix which has the same number of rows and columns as do A and B. The sum of A
and B, denoted A + B, is computed by adding corresponding elements of A and B.
It means,
5
SEMESTER 3
Task:
Write a program to perform matrix addition. Create a Two Dimensional Array, ask the user to enter
number of rows and columns. Keep the restriction in mind that rows and columns for a matrix must
be of same size. Prompt the user if unequal rows and columns are added. Input the elements with
the label of corresponding row and column. Output the result in a proper matrix format.
Algorithm:
Initialize int for row, column, 2D array one and two, sum of 2D array, i, j, k for iteration of
for loop.
Take input from user for rows and columns.
Keep a check on the input of user (if entered wrong the program must be ended).
Else, the program must ask the user to enter the elements for the matrixes. Enter the
elements for matrix number 1, then for matrix number 2.
Format of input of elements must follow the following format:
Enter element for matrix A 11 and so on.
For iterating/ loop through arrays, use for loop.
Write the formula for summation of arrays.
Output the result in matrix format:
2 3
4 5
Code:
6
SEMESTER 3
Output:
7
SEMESTER 3
Lab # 02
Theory:
Matrix Multiplication:
Matrices are frequently used in programming and are used to represent graph data structure,
in solving a system of linear equations and have many other applications. Applications of
matrix multiplication in computational problems are found in many fields including scientific
computing and pattern recognition, in seemingly unrelated problems such as counting the
paths through a graph.
To multiply a matrix by another matrix we need to do the "dot product" of rows and columns ...
what does that mean? Let us see with an example:
To work out the answer for the 1st row and 1st column:
The "Dot Product" is where we multiply matching members, then sum up:
We match the 1st members (1 and 7), multiply them, likewise for the 2nd members (2 and 9)
and the 3rd members (3 and 11), and finally sum them up.
8
SEMESTER 3
We can do the same thing for the 2nd row and 1st column:
And we get:
Task:
Write a program to perform matrix multiplication. Create a Two Dimensional Array, ask the user to
enter number of rows and columns. Keep the restriction in mind that the column of first matrix must
be equal to rows of second matrix. However the output matrix follows the constraint of Matrix 1 row
must be equal to Matrix 2 column. Prompt the user if wrong dimension is added. Input the elements
with the label of corresponding row and column. Output the result in a proper matrix format.
Algorithm:
Initialize/Declare int for matrix 1 row and column, matrix 2 row and column, 2D array A and
B, multiplication output 2D array, i, j, k variables for iteration of for loops.
Take input from user for rows and columns of matrix A and B.
Keep a check on the input of user (if entered wrong the program must be ended).
Else, the program must ask the user to enter the elements for the matrices.
Enter the elements for matrix number 1, then for matrix number 2.
Format of input of elements must follow the following format:
Enter element for matrix A 11 and so on.
For iterating/ loop through arrays, use for loop.
Initialize the multiply array with 0 (Zero).
Write the formula for multiplication of arrays.
Output the result in matrix format:
2 3
4 5
10
SEMESTER 3
Code:
11
SEMESTER 3
12
SEMESTER 3
Output:
13
SEMESTER 3
Lab # 03
Objective: Perform processing of string data structures using string processing functions.
Theory:
Suppose we want a program that manipulates people’s names. We could use the basic char data type as
our data structure. That is we could define 30 separate variables, char chr1, chr2, chr3 … chr30. Then
assign each one a character in a name. This would be very clumsy and hard work and inflexible. A better
data structure would be to create a string that enables manipulation of a string as a whole and as
individual characters.
For Example:
A string is an array of characters, a sequence of characters plus one special character. i.e. the end of
string character. A named constant NULL takes the value of ‘\0’.
char word[10]; //able to store a string of 9 chars (9 characters plus one NULL constant). Input and
Processing of Strings:
To take input of string array use getline() function. This function takes input of string as a whole line and
keeps taking the input until it encounters a null or new line character. (Stopping criteria)
cin.getline(stringName,Size,Stopping_Criteria); cin.getline(str1,20,'\
n');
There are many functions which can be defined on strings. Some important functions are:
14
SEMESTER 3
String copy: Creating another string which is a copy of the original or a copy of a part of the original.
The standard C++ library provides a string class type that supports all the operations mentioned above.
Use <string.h> for performing processing of strings.
A string has a certain length (the number of characters not including NULL. This is not the same as the
size of the array). Access of string is done in the following way:
FirstName[0] allows us to access the first character. To know the length of the string use strlen() function:
strlen(StringArrayName);
String Compare:
To compare two strings use strcmp() function. strcmp(string1, string2) returns an integer,
if (strcmp(FirstName, “Ali”) == 0)
String Copy:
strcpy(destination, source);
Which copies a string pointed to by source into a location pointed to by destination. The function
returns the destination pointer, dest. This is the equivalent of an assignment operation for data type,
STRING.
For Example:
strcpy(FirstName,”Dawood”);
String Concatenation:
15
SEMESTER 3
strcat(str1, str2);
It takes two strings, let’s say si and s2 and concatenates (i.e. joins) the two strings, s1 and s2, and
stores the result in s1. It returns s1, i.e. the pointer to the combined string. This is the equivalent of
the addition operator for strings.
For Example:
char a[10]=“Hello ”;
char b[10]=“World”;
strcat(a,b);
2
SEMESTER 3
Task:
1) Write a program to show your understanding of string processing functions. Your task is to
code a simple game of doors.
There are a total of three doors. Start opening them by giving the correct key.
On the right input you will move to the next door. On the wrong input your game will
end no matter to which door you have reached.
Take the input of string array using function of string library. Provide the hint to player
by calculating the length of real password that is already hard coded in the program.
Compare the typed-in and real password using appropriate string compare function.
2) Write a program of website link suggestion. Ask the user to enter the brand name for which
he/she wants a website to be created.
The brand name might contain capital letters. Write a function to convert
Uppercase to Lowercase using tolower() function of <ctype.h> library.
Move the converted brand name to website name using string processing’s copy
string function.
Take the input of domain name. You will provide 3 options of domains to user and
ask for a single selection.
i. .com
ii. .net
iii. .org
Use concatenating function to generate the website in a proper format. E.g
a. Brand/company name is Facebook.
b. Domain is .com.
c. Website suggested by your code: www.facebook.com
3
SEMESTER 3
Code:
(Task 1)
4
SEMESTER 3
Output:
(Task 2)
Output:
5
SEMESTER 3
LAB # 04
Theory:
Searching is an operation or a technique that helps finding the place of a given element or value in the
list. Any search is said to be successful or unsuccessful depending upon whether the element that is being
searched is found or not.
Linear Search:
This is the simplest method of searching an element in an array. It is not necessary for the array to be
sorted. Linear search searches for the element in a sequential manner. A linear search is made over all
items one by one. Every item is checked and if a match is found then that particular item is returned,
otherwise the search continues till the end of the data collection. If you have 100 items to search it
would require to look at every item in the input before the algorithm came across the desired value. It
is called linear because the time it takes to search is exactly correlated with the amount of items in the
search.
How it works?
Linear search is used on a collections of items. It relies on the technique of traversing a list from start to
end by exploring properties of all the elements that are found on the way. The pseudocode is:
{ print (current_index);
}}
In the example below, Linear search starts searching for the desired element from the 0th index till the
last index of array. If the element is found indicate it by initializing the flag value to 1. In case of the
6
SEMESTER 3
element not being found indicate the result by initializing the flag value to 0.
Let’s say the value to be searched is 11. The algorithm will start looking for the value from the index 0.
On index 0 the value stored is 10. As 10 is not equal to 11, the algorithm will move towards the next
index. The element will be found at the index 3 after completing 4 steps in total.
Task:
2) Expand the task 1, this time ask the user to enter the maximum size of array.
Ask the user to enter elements in array.
Search the element using linear search in the user defined array.
Output the result in the same manner as you did in the previous one.
2
SEMESTER 3
Code:
(Task 1)
Output:
3
SEMESTER 3
(Task 2)
Output:
4
SEMESTER 3
LAB # 05
Objective: Implement Binary search algorithm and search an element in a sorted array.
Theory:
Binary Search:
The second type of searching algorithm in data structures is Binary search. It gets its name
because the word binary means “of or relating to 2 things” and the algorithm works by splitting the input
into two parts until it finds the item that is being searched. It works on the principle of dividing and
conquering. Binary search is basically just a highly disciplined approach to the process of elimination. It’s
processing is faster than the algorithm of linear search. The requirement of binary search is that:
When binary search is used to perform operations on a sorted set, the number of iterations can always
be reduced on the basis of the value that is being searched.
How it works?
Binary search will start by examining the middle item. If that item is the one we are searching for, we
are done. If it is not the correct item, we can use the ordered nature of the list to eliminate half of the
remaining items. If the item we are searching for is greater than the middle item, we know that the
entire lower half of the list as well as the middle item can be eliminated from further consideration. The
item, if it is in the list, must be in the upper half. The process is repeated with the upper half. Start at
the middle item and compare it against what we are looking for. Again, we either find it or split the list
in half, therefore eliminating another large part of our possible search space.
binarySearch(low,high,key)
{ while(low<=high)
{ mid=(low+high)/2;
if(a[mid]<key)
{ low=mid+1; }
2
SEMESTER 3
else if(a[mid]>key)
{ high=mid-1; }
Consider the above array, if the element 37 is to be searched using Linear search approach then the
process will take a total of 11 steps. If the same element is searched using Binary search algorithm then
the process will work the following way:
The value of low and high at initial is 0 and 16. The value of mid can be calculated using the following
formula:
Mid=low+high/2
3
SEMESTER 3
The value 37 is then matched with index 8’s value which is 23. As 37 is greater than the mid value, low is
now set to mid+1. Again the mid value is calculated using the new value of low and old value of high.
Over all the searching will take a total of 3 steps.
Task:
1- Write a program to show your understanding of binary search algorithm by implementing its
program.
Ask the user to enter the max size of array then take input of array elements.
Ask the user to search for an element in array and know its index position.
Search the element using binary search algorithm.
If the element is found return the index number of the found element of array.
Output the result in this format:
The number: 10 is found at index position: 0
2- Task 1 was the iterative method to search element, this time make the binary search
algorithm recursive.
Ask the user to enter elements in array.
Search the element using binary search in the user defined array.
Output the result in the same manner as you did in the previous one.
4
SEMESTER 3
Code:
(Task 1)
5
SEMESTER 3
(Task 2)
6
SEMESTER 3
Output:
Task 1 output
Task 2 output
7
SEMESTER 3
LAB # 06
Theory:
Sorting in DSA:
Sorting is a process of ordering or placing a list of elements from a collection in some kind of order.
It is nothing but storage of data in sorted order. Sorting can be done in ascending and descending
order. It arranges the data in a sequence which makes searching easier.
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Quick Sort
5. Heap Sort
Bubble Sort:
Working of Algorithm:
For the sorting in ascending order, the algorithm will work in the following way:
1. Starting with the first element(index = 0), compare the current element with the next
element of the array.
2. If the current element is greater than the next element of the array, swap them.
8
SEMESTER 3
3. If the current element is less than the next element, move to the next element. Repeat Step 1.
For sorting in descending order swap in step 2 if current element is less than the next element of the
array.
An Example:
Pseudocode:
Array[i]>Array[i+1]
temp=Array[i+1]
A[i+1]=Array[i]
A[i]=temp
Task:
9
SEMESTER 3
Task 1:
Code:
Output:
10
SEMESTER 3
Task 2:
Code:
Output:
11
SEMESTER 3
LAB # 07
Theory:
Insertion Sort:
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
Consider you have 10 cards out of a deck of cards in your hand. And they are sorted, or arranged in the
ascending order of their numbers. If another card is given to you, and you are asked to insert the card in
just the right position, so that the cards in your hand are still sorted. What will you do? Well, you will
have to go through each card from the starting or the back and find the right position for the new card,
comparing its value with each card. Once you find the right position, you will insert the card there.
Similarly, if more new cards are provided to you, you can easily repeat the same process and insert the
new cards and keep the cards sorted too. This is exactly how insertion sort works. It starts from the
index 1(not 0), and each index starting from index 1 is like a new card, that you have to place at the
right position in the sorted subarray on the left.
It is efficient for smaller data sets, but very inefficient for larger lists.
Insertion Sort is adaptive, that means it reduces its total number of steps if a partially sorted
array is provided as input, making it efficient.
It is better than Selection Sort and Bubble Sort algorithms.
It is a stable sorting technique, as it does not change the relative order of elements which are
equal.
12
SEMESTER 3
An Example:
Step 1: The second element of an array is compared with the elements that appears before
it (only first element in this case). If the second element is smaller than first
element, second element is inserted in the position of first element. After first step, first
two elements of an array will be sorted.
Step 2: The third element of an array is compared with the elements that appears before it
(first and second element). If third element is smaller than first element, it is inserted in the
position of first element. If third element is larger than first element but, smaller than second
element, it is inserted in the position of second element. If third element is larger than both the
elements, it is kept in the position as it is. After second step, first three elements of an array
will be sorted.
Step 3: Similarly, the fourth element of an array is compared with the elements that appears
before it (first, second and third element) and the same procedure is applied and that element
is inserted in the proper position. After third step, first four elements of an array will be
sorted.
13
SEMESTER 3
Note: If there are n elements to be sorted. Then, this procedure is repeated n-1 times to get sorted list
of array.
Pseudocode:
for i = 1 to n
temp ← A [i]
–1
A[j+1] ← A[j]
j←j–1
A[j+1] ← temp
Task:
Task 1:
Code:
14
SEMESTER 3
Output:
Task 2:
Code:
Output:
2
SEMESTER 3
3
SEMESTER 3
LAB # 08
Theory:
Selection Sort:
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison- based
algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted
part at the right end.
We can say that the algorithm maintains two subarrays in a given array.
1) For the first position in the sorted list, the whole list is scanned sequentially. The first position
where 14 is stored presently, we search the whole list and find that 10 is the lowest value.
2) So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the list,
appears in the first position of the sorted list.
3) For the second position, where 33 is residing, we start scanning the rest of the list in a linear
manner.
4) We find that 14 is the second lowest value in the list and it should appear at the second place.
We swap these values.
4
SEMESTER 3
5) After two iterations, two least values are positioned at the beginning in a sorted manner.
6) The same process is applied to the rest of the items in the array.
7) The Final Output.
1) Initially, the sorted part is empty and the unsorted part is the entire list.
2) The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues moving
unsorted array boundary by one element to the right.
3) In every iteration of selection sort the same process is repeated.
Pseudocode:
for i = 0 to n-1 {
A[min]=A[i]
for j = i+1 to n { if
(A[min] >A[j]) {
min=j; A[min]=A[j]
}}
swap(A[i], A[min])
5
SEMESTER 3
Task:
1) Write a program to show your understanding of sorting by implementing selections sort algorithm.
Ask the user to enter the max size of array then take input of array elements.
Sort the array using selection sort algorithm in ascending order.
2) Make change in your previous algorithm. This time perform sorting in descending order.
Task 1:
Code:
Output:
6
SEMESTER 3
Task 2:
Code:
Output:
7
SEMESTER 3
LAB # 09
Theory:
Quick Sort:
• Quick sort is a Divide and Conquer algorithm. It is also called partition-exchange sort.
• Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data
into smaller arrays.
• Its approach is based on the idea of choosing one element as a pivot element and partitioning
the array around it such that: Left side of pivot contains all the elements that are less than
the pivot element Right side contains all elements greater than the pivot.
1. Pivot element can be any element from the array, it can be the first element, the last
element, the median one or any random element.
2. After selecting an element as pivot (Assuming that it is the last index of the array), we divide
the array for the first time.
3. In quick sort, it is termed as partitioning. It is not simple breaking down of array into 2
subarrays but, the array elements are so positioned that all the elements smaller than the
pivot will be on the left side of the pivot and all the elements greater than the pivot will be on
the right side of it.
4. Pivot element will be at its final sorted position. The elements to the left and right, may not be
sorted.
5. Pick subarrays, elements on the left of pivot and elements on the right of pivot, and we
perform partitioning on them by choosing a pivot in the subarrays.
An Example:
Applying the Quick Sort Algorithm. First set the initial value of pivot (which is the right most element
in this case). The value for right element (size of array -1) and the value for left element (0).
8
SEMESTER 3
Comparing the Pivot with the left and right parts of the array, all the elements smaller than the pivot
must be placed at the left side of the pivot. All the elements greater than the pivot must be placed at
the right side.
After placing the elements the array is divided further into two more parts. The left partition and the
right partition. Applying the same above step of calculating pivot element and comparing it with the
rest of elements of the array on both partitions. This technique will sub- divide the array’s partitions
too. After sorting the sub-arrays, whole array will become sorted.
9
SEMESTER 3
Pseudocode:
/* left --> Starting index, right --> Ending index */ quickSort(arr[], left,
right)
right place */
pi + 1, right); // After pi
Task:
1. Write a Quick Sort Program in C++. Sort the array in ascending order. Use the rule of last
index as pivot element.
2. Write the Quick sort program to sort the array in descending order. Use the rule of last
index as pivot element.
10
SEMESTER 3
Task 1:
Code:
11
SEMESTER 3
Output:
Task 2:
Code:
12
SEMESTER 3
Output:
13
SEMESTER 3
LAB # 10
Theory:
Merge Sort:
Just like Quick Sort, Merge Sort is a Divide and Conquer algorithm. It is one of the most popular sorting
algorithms and a great way to develop confidence in building recursive algorithms. It divides input array
in two halves, calls itself for the two halves and then merges the two sorted halves.
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it
is only one element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping
the new list sorted too.
Step 2 − divide the list recursively into two halves until it can no more be divided. Step 3 −
14
SEMESTER 3
Example:
14 33 27 10 35 19 42 44
We know that merge sort first divides the whole array iteratively into equal halves unless the atomic
values are achieved. We see here that an array of 8 items is divided into two arrays of size 4.
This does not change the sequence of appearance of items in the original. Now we divide these two
arrays into halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please note the color
codes given to these lists.
We first compare the element for each list and then combine them into another list in a sorted manner.
We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list of 2 values
we put 10 first, followed by 27. We change the order of 19 and 35 whereas 42 and 44 are placed
sequentially.
In the next iteration of the combining phase, we compare lists of two data values, and merge them into
a list of found data values placing all in a sorted order.
After the final merging, the list should look like this
15
SEMESTER 3
2
SEMESTER 3
Pseudocode:
MergeSort (Array(First..Last))
Begin
Array
Else
MergeSort(Array(Middle+1..Last)) ResultArray =
Merge(LeftHalfArray, RightHalfArray)
Return ResultArray
EndIf
End MergeSort
Task:
1. Write a program in C++ to sort the array using Merge sort algorithm. Sort in ascending order.
2. Sort the array in descending order using Merge Sort algorithm. Task
1:
Code:
3
SEMESTER 3
Output:
4
SEMESTER 3
Task 2:
Code:
Output:
5
SEMESTER 3
LAB # 11
Theory:
Stack ADT:
A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is type of
linear data structure. It follows LIFO (Last In First Out) property. It is named stack as it behaves like a
real-world stack, for example – a deck of cards or a pile of plates, etc.
A real-world stack allows operations at one end only. For example, we can place or remove a card or
plate from the top of the stack only. Similarly, stack allows all the operations at one end only. The two
operations are performed on a stack. PUSH & POP. When inserting an item in a stack, this is called
PUSH operation. When removing an item from stack, this is called POP operation. At any given time the
TOP of the stack is accessible. It always points to element recently inserted. If the stack is empty and
POP operation is applied, it gives an error of Stack Under Flow. If the stack is full or reaches the MAX
SIZE and PUSH operation is applied, it gives an error of Stack Over Flow.
Stack Representation:
Initialization of stack.
Insertion into stack (push operation). [If stack is Empty or having Space].
Deletion from stack (pop operation). [If stack is Full or having Elements].
Throw the error of Stack Under Flow if stack is Empty and POP operation is applied.
Throw the error of Stack Over Flow if stack is Empty and PUSH operation is applied.
6
SEMESTER 3
Example:
Algorithm:
TOP = -1;
Push Operation:
Exit;
Otherwise
End of IF
Exit
Pop Operation:
IF TOP = -1 then
Exit;
Otherwise
7
SEMESTER 3
TOP=TOP – 1;
End of IF
Exit
Stack is full:
STATUS = true;
Otherwise STATUS
= false; End of IF
Exit
Stack is Empty:
IF TOP = -1 then
STATUS = true;
Otherwise STATUS
= false; End of IF
Exit
Task:
• Implement the stack ADT. Make a class of stack and perform the task using array Data
structure. Following operations must be performed.
1. Insertion in Stack.
5. Exit.
8
SEMESTER 3
Code:
9
SEMESTER 3
Output:
2
SEMESTER 3
LAB # 12
Theory:
Queue ADT:
Queue Representation:
3
SEMESTER 3
Working:
1. Initialization of queue.
2. Insertion into queue ( enqueue operation). [If queue is Empty Or having Space].
3. Deletion from queue (dequeue operation). [If queue is Full Or having Elements].
4. Throw the error of Queue Under Flow if queue is Empty and DEQUEUE operation is
applied.
5. Throw the error of Queue Over Flow if queue is Empty and ENQUEUE operation is
applied.
6. Use PEEK Function to check the value at FRONT Part.
Example:
4
SEMESTER 3
Algorithm:
PEEK()
return queue[front]
end procedure
IS FULL()
return true
else
return false
endif
end procedure
IS EMPTY()
return true
else
return false
endif
end procedure
Enqueue()
procedure enqueue(data) if
queue is full
return overflow
5
SEMESTER 3
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
Dequeue()
procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front ← front + 1
return true
end procedure
Task:
• Implement the queue ADT. Make a class of queue and perform the task using array Data
structure.
1. Insertion in Queue.
6. Exit.
6
SEMESTER 3
Code:
7
SEMESTER 3
8
SEMESTER 3
Output:
9
SEMESTER 3
LAB # 13
Objective Design a Linked list and perform searching, insertion and deletion operations of a linked
list.
Theory:
Linked List:
A linked list is a sequence of data structures, which are connected together via links. Each link
contains a connection to another link. Linked list is the second most-used data structure after array.
Following are the important terms to understand the concept of Linked List.
• Link − Each link of a linked list can store a data called an element.
• Next − Each link of a linked list contains a link to the next link called Next.
• LinkedList − A Linked List contains the connection link to the first link called First.
Linked list can be visualized as a chain of nodes, where every node points to the next node.
Working:
2. Each link carries a data field(s) and a link field called next.
3. Each link is linked with its next link using its next link.
4. Last link carries a link as null to mark the end of the list.
Basic Operations:
10
SEMESTER 3
Read(Data(first));
NEXT(First)=NULL;
X=new node;
Read(Data(X))
NEXT(X)=NULL;
For Loop]
END
Display:
count=0;
count=count+1;
END
11
SEMESTER 3
Searching:
If first=NULL then{
STOP
[end of while]
END
X=new node;
Read(DATA(X);
If (FIRST=NULL) then
First=X;
NEXT(X)=NULL;
Else
NEXT(X)=First;
First=X;
} END
12
SEMESTER 3
Ptr=List;
If (DATA(ptr)=’VAL’) then
X=new node
Read (DATA(X);
NEXT(X)=NEXT(ptr)
NEXT(ptr)=X; BREAK;
ptr=NEXT(ptr)
[end of while]
END.
ptr=LIST
If(data(ptr)=’VAL’) then
X=new node;
Read DATA(X);
NEXT(X)=LIST;
LIST=X;
STOP;
back=ptr;
13
SEMESTER 3
ptr=NEXT(ptr);
If(DATA(ptr)=’VAL’)then
X=new node;
Read DATA(X);
NEXT(X)=ptr;
NEXT(back)=X;
EXIT;
END
If (DATA(list)=’VAL’)then
Ptr=LIST;
LIST=NEXT(list);
Delete ptr;
Stop;
Back=list;
Ptr=list;
If(DATA(ptr)=’VAL’) then
NEXT(back)=NEXT(ptr);
Delete ptr;
14
SEMESTER 3
Exit;}
back=ptr;
ptr=next(ptr);
END
Task:
Implement the Linked list data structure. Following operations must be performed.
4. Exit.
Code:
15
SEMESTER 3
Output:
16
SEMESTER 3
LAB # 14
Objective Define performance analysis (Time and space complexity) of given algorithms.
Theory:
Performance analysis:
Performance analysis of an algorithm depends upon two factors i.e. amount of memory used and
amount of compute time consumed on any CPU. Formally they are notified as complexities in terms of:
1. Space Complexity.
2. Time Complexity.
Space Complexity:
The amount of memory it needs to run to completion i.e. from start of execution to its
termination. Space need by any algorithm is the sum of following components:
1. Fixed Component.
2. Variable Component.
Fixed Component: This is independent of the characteristics of the inputs and outputs. This part
includes: Instruction Space, Space of simple variables, fixed size component variables, and constants
variables.
Variable Component: This consist of the space needed by component variables whose size is
dependent on the particular problems instances(Inputs/Outputs) being solved, the space needed by
referenced variables and the recursion stack space is one of the most prominent components. Also this
included the data structure components like Linked list, heap, trees, graphs etc.
Therefore the total space requirement of any algorithm 'A' can be provided as:
Among both fixed and variable component the variable part is important to be determined
accurately, so that the actual space requirement can be identified for an algorithm 'A'. To identify
the space complexity of any algorithm following steps can be followed:
17
SEMESTER 3
4. Sometimes more complex measures of the interrelationships among the data items can used.
5. For iterative loops the complexity is 1 or constant.
6. For arrays the complexity is effected by the size of array i.e if there is an array arr[n] then
the complexity will be counted in terms of n.
For calculating the space complexity, we need to know the value of memory used by different type of
datatype variables, which generally varies for different operating systems, but the method for
calculating the space complexity remains the same.
Example:
int z = a + b + c;
return(z);
In the above expression, variables a, b, c and z are all integer types, hence they will take up 4 bytes
each, so total memory requirement will be (4(4) + 4) = 20 bytes, this additional 4 bytes is for return
value. And because this space requirement is fixed for the above example, hence it is called Constant
Space Complexity.
Example:
18
SEMESTER 3
x = x + a[i];
return(x);
In the above code, 4*n bytes of space is required for the array a[] elements. 4 bytes each for x, n, i and
the return value. Hence the total memory requirement will be (4n + 12), which is increasing linearly with
the increase in the input value n, hence it is called as Linear Space Complexity. Similarly, we can have
quadratic and other complex space complexity as well, as the complexity of an algorithm increases. But
we should always focus on writing algorithm code in such a way that we keep the space complexity
minimum.
Example:
Algorithm Sum(number,size)\\ procedure will produce sum of all numbers provided in 'number' list
result=0.0;
result;
In above example, when calculating the space complexity we will be looking for both fixed and variable
components. here we have Fixed components as 'result','count' and 'size' variable there for total space
required is three(3) words. Variable components is characterized as the value stored in 'size' variable
(suppose value store in variable 'size 'is 'n'). because this will decide the size of 'number' list and will
also drive the for loop. therefore if the space used by size is one word then the total space required by
'number' variable will be 'n'(value stored in
19
SEMESTER 3
variable 'size'). therefore the space complexity can be written as Space(Sum) = 3 + n; or O(n) simply.
Time Complexity:
The amount of computer time it needs to run to completion. The time taken by a program is the sum of
the compile time and the run/execution time . The compile time is independent of the
instance(problem specific) characteristics. following factors effect the time complexity:
• An assignment statement or comparison which does not involve any calls to other
algorithm is counted as one step.
• For iterative statements we consider the steps count only for the control part of the
statement etc.
• Any other statement which is bundled in the iterative statement is effected by the loop.
Asymptotic analysis of an algorithm refers to defining the mathematical boundation/framing of its run-
time performance. Using asymptotic analysis, we can very well conclude the best case, average case,
and worst case scenario of an algorithm.
• Asymptotic analysis refers to computing the running time of any operation in mathematical
units of computation. For example, the running time of one operation is computed as f(n) and
may be for another operation it is computed as g(n2). This means the first operation running
time will increase linearly with the increase in n and the running time of the second operation
will increase exponentially when n increases.
20
SEMESTER 3
Similarly, the running time of both operations will be nearly the same if n is significantly small.
Asymptotic Notations:
Following are the commonly used asymptotic notations to calculate the running time
complexity of an algorithm.
1. Ο Notation
2. Ω Notation
3. θ Notation
Big Oh Notation, Ο:
The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It
measures the worst case time complexity or the longest amount of time an algorithm can possibly take
to complete.
Omega Notation, Ω
The notation Ω(n) is the formal way to express the lower bound of an algorithm's running time. It
measures the best case time complexity or the best amount of time an algorithm can possibly take to
complete.
21
SEMESTER 3
Theta Notation, θ:
The notation θ(n) is the tight bound or we can say formal way to express both the lower bound
nd the upper bound of an algorithm's running time. It is represented as follows:
We always consider choosing the worst case complexity for time complexity analysis. Choose
the average case when Best and worst case give the same analysis.
22
SEMESTER 3
Example:
1+1+(n+1)+(n*1)+n*(n*1)+(n*n)+(n*n)+(n*1) 2+n+n+n^2+n^2+n^2+n
Supposing constant as C…
3n+3n^2+C
Considering the highest term and neglecting the coefficients and constants.
O(log n):
One place where you will hear about O(log n) time complexity the first time is Binary search
algorithm. Consider a sorted array of 16 elements. For the worst case, let us say we want to search
for the number 13.
2
SEMESTER 3
Since 13 is less than pivot, we remove the other half of the array
Repeating the process for finding the middle element for every sub-array
You can see that after every comparison with the middle term, our searching range gets divided into
half of the current range.
So, for reaching one element from a set of 16 elements, we had to divide the array 4 times, We can
say that,
3
SEMESTER 3
Simplified Formula
Generalization
Final result
A quantity representing the power to which a fixed number (the base) must be raised to
produce a given number.
Logarithmic form
4
SEMESTER 3
Task:
Calculate the time and/or space complexity of the given algorithms. For time complexity calculate
only the best and worst case. For space complexity calculate only the worst case.
5
SEMESTER 3
ENDLOOP
ENDFUNCTION
1) Matrix Addition (Space Complexity):
= a[i] + b[j];
Output:
1) Worst case Time complexity = O(n). Best case Time complexity = Ω (1).
2) Worst case Time complexity = O(n2). Best case Time complexity = Ω (n2).
3) Worst case Space complexity = O(n).
4) Worst case Space complexity = O(n).
6
SEMESTER 3
LAB # 15
Objective Develop the algorithm of Binary search tree (BST) and perform insertion, traversal and
deletion of nodes in a BST.
Theory:
• Trees are well-known as a non-linear data structure. They don’t store data in a linear
way. They organize data hierarchically.
• Each node contains a value or data, and it may or may not have a child node.
• The first node of the tree is called the root. If this root node is connected by another node,
the root is then a parent node and the connected node is a child.
• All Tree nodes are connected by links called edges. It’s an important part of trees,
because it’s manages the relationship between nodes.
• Leaves are the last nodes on a tree. They are nodes without children. Like real trees, we have
the root, branches, and finally the leaves.
Binary trees:
“In computer science, a binary tree is a tree data structure in which each node has at the most two
children, which are referred to as the left child and the right child.”
• Binary tree is that it is a collection of nodes. Each node has three attributes: value, left child,
and right child.
7
SEMESTER 3
• Path − Path refers to the sequence of nodes along the edges of a 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.
• Leaf − The node which does not have any child node is called the leaf node.
• Visiting − Visiting refers to checking the value of a node when control is on the node.
• Levels − Level of a node represents the generation of a node. If the root node is at level 1, then
its next child node is at level 2, its grandchild is at level 3, and so on. Level = Depth+1.
“A binary tree is a Binary Search Tree (BST) if the key of the node is greater than all the nodes in its
left subtree and is smaller than all the nodes in its right subtree.”
8
SEMESTER 3
Binary Search tree exhibits a special behavior. A node's left child must have a value less than its parent's
value and the node's right child must have a value greater than its parent value.
Insertion:
Look for the root node, if it is empty add the data on root else keep going to either right subtree or left
subtree depending on the value and when we reach a point left or right subtree is null, we put the new
node there.
If node == NULL
return createNode(data) if
return node;
Searching:
9
SEMESTER 3
Look for the root node first, if the search key matches with the root node then it is the target node else
If the value is below root, we can say for sure that the value is not in the right subtree; we need to only
search in the left subtree and if the value is above root, we can say for sure that the value is not in the
left subtree; we need to only search in the right subtree.
display(root->data)
preorder(root->left)
preorder(root->right)
In order Traversal:
inorder(root->left)
display(root->data)
inorder(root->right)
postorder(root->left)
postorder(root->right)
display(root->data)
Deletion:
• If the node is leaf (both left and right will be NULL), remove the node directly and free its
memory.
• If the node has only right child (left will be NULL), make the node points to the right node
and free the node.
10
SEMESTER 3
• If the node has only left child (right will be NULL), make the node points to the left node and
free the node.
return NULL;
root->left = removeNode(root->left,val);
Else
return NULL;
free(root);
return temp;
free(root);
return temp;
else
11
SEMESTER 3
root->key = rightMin;
root->right = removeNode(root->right,rightMin);
Task:
Insertion
In order traversal
Pre order Traversal
Post order Traversal
Deletion
Exit
Code:
12
SEMESTER 3
13
SEMESTER 3
14
SEMESTER 3
15
SEMESTER 3
16
SEMESTER 3
Output
17
SEMESTER 3
18