DSA LAB Manual Muhammad

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 100

ZIAUDDIN UNIVERSITY

FACULTY OF ENGINEERING SCIENCE TECHNOLOGY AND


MANAGAMENT

Laboratory Manual
For

Data Structures & Algorithms

(CS- 211)

Prepared by:
Guided by:

Approved by:

DEPARTMENT OF BE ELECTRICAL ENGINEERING


Certificate

This is to certify that Mr. / Ms….................................................of


Third Semester, Second Year, Department of Software
Engineering bearing Roll No. ………….……. has completed the
necessary lab work for the course of Data Structures &
Algorithms prescribed by the Ziauddin University, Faculty of
Engineering Science and Technology, under my supervision for the
academic session ………………

Course Teacher Lab Teacher


Name: Name:

Designation: Designation:

Department: Department:
SOFTWARE LAB RUBRICS FOR ASSESSING IN-LAB PERFORMANCE
PLO-2 (PROBLEM ANALYSIS)

CRITERIA EXCEEDS MEETS DEVELOPING UNSATISFACTOR SCORE


EXPECTATION EXPECTATION (2-5) Y (0-10)
(10) (6-9) (0-2)
Ability to use -Student was familiar -Student was -Student -Student demonstrated
software with the software and familiar with the demonstrated an little or no ability to
was able to use software and ability to use the perform experiment
additional features of required minimal software but and required
the software that were help from the required assistance unreasonable amount
not available in instructor to from the instructor. of assistance from
instruction set. perform the instructor.
experiment.
Ability to -Student followed the -Student followed -Student had -Student had difficulty
follow instructions with no the instructions in difficulty with reading the procedure
procedure assistance. the procedure with some of the and following
and/or little or no procedure and directions.
design a -Student performed assistance. needed
procedure additional experiments clarification from -If procedure was not
for or tests beyond those -If procedure was the instructor. provided, student was
experiment required in not provided, the incapable of designing
instructions. student was able -If, procedure was a set of experiments to
to determine an not provided, the satisfy given lab
-If procedure to student needed objectives.
accomplish an
appropriate set of
some direction in
objective is not experiments to deciding what set -The data taken was
provided, the student run to produce of experiments to essentially useless.
developed a systematic stable data and perform to satisfy
set of tests to satisfy the lab the lab objectives.
accomplish objective. objectives.
Ability to -Student developed a -Student -Student was able -Student demonstrated
troubleshoot good systematic demonstrated the to identify the little or no ability to
software procedure for testing ability to test problems in troubleshoot software
software code that software code in software code but code for the lab.
allowed for quick order to identify required some
identification of technical assistance in fixing
problems. problems, and was some of the
able to solve any problems.
-Student is good at problems with
analyzing and quickly little or no
solving all technical assistance.
problems.
Q&A -Able to explain -Able to explain -Able to explain -Unable to explain
program design and most of the some program program design or
fundamental concepts program design design and relevant answer relevant
correctly and provide and relevant fundamental fundamental concepts.
alternative solutions. fundamental concepts.
concepts.
REPORT WRITING LAB RUBRICS FOR ASSESSING IN-LAB PERFORMANCE
PLO-2 (PROBLEM ANALYSIS)

CRITERIA EXCEEDS MEETS DEVELOPING UNSATISFACTOR SCORE


EXPECTATION EXPECTATION (2-5) Y (0-10)
(10) (6-9) (0-2)
Data -Student demonstrates -Experimental -Experimental data -Experimental data is
Presentation diligence in creating a data is presented is presented in poorly presented.
set of visually in appropriate appropriate format
appealing tables and/or format with only but some -Graphs or tables are
graphs that effectively significant errors poorly constructed
a few minor
present the are still evident. with several of the
experimental data.
errors or following errors: data
omissions. -Tables could be is missing or incorrect,
better organized or units are not included,
some titles, labels, axis labeled, or titles
or units of measure missing.
are missing.
Data -Student provides a -Student has -Student has -Student has simply
Analysis very focused and analyzed the analyzed the data, re-stated what type of
accurate analysis of the data, observed observed trends, data was taken with no
data. All observations trends, and and compared attempt to interpret
are stated well and experimental trends, explain
compared
clearly supported by the results with discrepancies, or
data.
experimental theoretical results. evaluate the validity of
results with the data in terms of
theoretical - Any discrepancies relevant theory.
results. are not adequately
addressed. -Student lacks
-Any understanding of the
discrepancies are -Some observations importance of the
adequately that should have results.
addressed. been made are
missing or poorly
-All expected supported.
observations are
made.
Writing -Lab report has no -Lab report has -Lab report has -Lab report has several
Style grammatical and/or very few some grammatical grammatical and/or
spelling errors. grammatical and/or spelling spelling errors and
and/or spelling errors and is fairly sentence construction
-All sections of the errors. readable. is poor.
report are very well-
written and technically -The sentence - Student make -Student rarely uses
accurate. flow is smooth. effective use of technical terms or uses
technical terms and them incorrectly and
-Student uses rarely resorts to too often resorts to
technical terms jargon or cliches. jargon or cliches.
effectively and
accurately.
SEMESTER 3

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

7 Develop an Insertion sort program to sort an unsorted array. P – 04


Construct a Selection sort algorithm to sort an array of unsorted
8 P – 04
elements.

9 Implementation of the algorithm of Quick sort. P – 02

10 Perform sorting of elements in an array using Merge sort algorithm. P - 02

11 Implementation of Stack ADT algorithm. P - 02


Demonstrate your understanding of Queue ADT by implementing its
12 P - 03
algorithm.
Design a Linked list and perform searching, insertion and deletion
13 P - 05
operations of a linked list.
Define performance analysis (Time and space complexity) of given
14 P – 05
algorithms.
Develop the algorithm of Binary tree and perform searching, insertion
15 P - 04
and deletion of nodes in a binary tree.

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:

Linear Data Structure:

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.

The different types of linear data structures are:

 Array
 Stack
 Queue
 Linked List

Non-Linear Data Structure:

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

Relationship between Data Structures and Algorithms:

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.

Contiguous and Non-Contiguous:

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:

One Dimensional Array:

type arrayName [arraySize];

Two Dimensional Array (Matrix):

type arrayName [arraySize][arraySize];

Initializing arrays:

One Dimensional Array:

int balance[5] = {1000, 2, 3, 17, 50};

Two Dimensional Array:

int matrix[2][2] = {1000, 2, 3, 17, 50, 4, 70, 30};

A matrix can be added, subtracted, multiplied and transposed.

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,

Pseudocode for Matrix Addition:

 Let the matrices be A, B be the input matrices


 Let the matrix holding the sum be called Sum.
 Check if number of rows and columns for matrix A and B are same.
 For I in 1 .. n-1 loop
 For J in 1.. n-1 loop
o Sum(I,J) := A(I,J) + B(I,J)
 Return matrix Sum

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

Objective: Show your knowledge of array data structures by coding matrix


multiplication program.

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.

The definition of matrix multiplication is that if C = AB for an n × m matrix A and


an m × p matrix B, then C is an n × p matrix with entries,

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:

(1, 2, 3) • (7, 9, 11) = 1×7 + 2×9 + 3×11 = 58

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.

Here it is for the 1st row and 2nd column:

8
SEMESTER 3

We can do the same thing for the 2nd row and 1st column:

(4, 5, 6) • (7, 9, 11) = 4×7 + 5×9 + 6×11 = 139

And for the 2nd row and 2nd column:

(4, 5, 6) • (8, 10, 12) = 4×8 + 5×10 + 6×12 = 154

And we get:

Pseudocode for Matrix Multiplication:

 Input: matrices A and B


 Let C be a new matrix of the appropriate size
 For i from 1 to n:
 For j from 1 to p:
 Let sum = 0
 For k from 1 to m:

Set sum ← sum + Aik × Bkj
 Set Cij ← sum
 Return C
9
SEMESTER 3

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:

Strings and Data Structures:

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.

String literal – a sequence of characters in double quotes.

For Example:

“This is a string”, “Hello world”, “mydata.dat”

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:

String length: Determines length of a given string.

String concatenation: Concatenation of two or more strings.

14
SEMESTER 3

String copy: Creating another string which is a copy of the original or a copy of a part of the original.

String compare: Searching for a query string in given string.

The standard C++ library provides a string class type that supports all the operations mentioned above.
Use <string.h> for performing processing of strings.

String Indexes and String Length:

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,

 > 0 if string1 is “bigger” than string2


 < 0 if string1 is “smaller” than string2
 0 (False) if string1 is the same as string2 It

compares each string a character at a time.

if (strcmp(FirstName, “Ali”) == 0)

cout << “Correct name” << endl;

String Copy:

To copy the value of a string to another use strcpy() function:

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”);

“Assigns” the string “Dawood” to FirstName.

String Concatenation:
15
SEMESTER 3

To concatenate the strings use strcat() function.

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);

It will concatenate two strings like this: Hello World.

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

Objective: Demonstrate your understanding of linear search by implementing its algorithm.

Theory:

Searching and its algorithms in Data structures:

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.

The standard algorithms for searching are:

 Linear or Sequential Search.


 Binary Search.

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.

(100 items/input =100 checks)

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:

for(start to end of array)

if (current_element equals to searchedElement)

{ 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:

1) Write a program to show your understanding of linear search algorithm by


implementing its program.
 Hard code the array of 5 elements.
 Calculate the total size of the array.
 Ask the user to search for an element in array and know its index position.
 Search the element using linear search algorithm.
 If the element is found initialize the flag value to 1, else 0.
 Output the result in this format:
The number: 10 is found at index position: 0

(Assuming you found the number 10 at index 0).

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:

“Array must be in a sorted order”

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.

Pseudocode for Binary Search:

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; }

else { return mid; //key found

} return -1; //key not found

Comparing Linear Search with Binary Search:

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

Mid= 0+16/2 => 8.

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

(Assuming you found the number 10 at index 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

Objective: Build a Bubble sort algorithm to sort the elements of an array.

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.

Algorithms for Sorting:

1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Quick Sort
5. Heap Sort

Bubble Sort:

 Bubble sort is a simple and well-known sorting algorithm.


 It is used for sorting 'n' (number of items) elements.
 It compares all the elements one by one and sorts them based on their values.
 Bubble sort algorithm starts by comparing the first two elements of an array and
swapping if necessary.
 If you want to sort the elements of array in ascending order and if the first element is
greater than second then, you need to swap the elements but, if the first element is smaller
than second, you mustn't swap the element.
 Then, again second and third elements are compared and swapped if it is necessary and this
process go on until last and second last element is compared and swapped.
 This completes the first step of bubble sort.
 If there are n elements then the steps will be n-1.

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:

for step=0 to Array.length-1

for i=0 to Array.length-step-1 if

Array[i]>Array[i+1]

temp=Array[i+1]

A[i+1]=Array[i]

A[i]=temp

Task:

1) Write a program to show your understanding of sorting by implementing bubble sort


program.
 Ask the user to enter the max size of array then take input of array elements.
 Sort the array using bubble sort algorithm in ascending order.
2) Make change in your previous algorithm. This time perform sorting in descending order.

9
SEMESTER 3

Task 1:

Code:

Output:

10
SEMESTER 3

Task 2:

Code:

Output:

11
SEMESTER 3
LAB # 07

Objective: Develop an Insertion sort program to sort an unsorted array.

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:

Working Of the Algorithm:

 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]

// Insert A[i] into the sorted sequence A[1..i-1] j← i

–1

while j >= 0 and A[j] > temp

A[j+1] ← A[j]

j←j–1

A[j+1] ← temp

Task:

1) Write a program to show your understanding of sorting by implementing insertion


program.
 Ask the user to enter the max size of array then take input of array elements.
 Sort the array using insertion sort algorithm in ascending order.
2) Make changes in your previous algorithm. This time perform sorting in descending order.

Task 1:

Code:

14
SEMESTER 3

Output:

Task 2:

Code:

Output:

2
SEMESTER 3

3
SEMESTER 3

LAB # 08

Objective: Construct a Selection sort algorithm to sort an array of unsorted elements.

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) The subarray which is already sorted.

2) Remaining subarray which is unsorted.


 This algorithm is not suitable for large data sets.
An Example:

Consider the above depicted 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.

Working of the Algorithm:

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 {

min = i // max=i in case of descending order

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

Objective: Implementation of the algorithm of Quick sort.

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.

Working of the Algorithm:

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:

Consider the example of an unsorted array below:

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)

if (left < right)

/* pi is partitioning index, arr[pi] is now at

right place */

pi = partition(arr, left, right);

quickSort(arr, left, pi - 1); // Before pi quickSort(arr,

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

Objective: Perform sorting of elements in an array using Merge sort algorithm.

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.

Working of the Algorithm:

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 1 − if it is only one element in the list it is already sorted, return.

Step 2 − divide the list recursively into two halves until it can no more be divided. Step 3 −

merge the smaller lists into new list in sorted order.

14
SEMESTER 3

Example:

Consider the array given below:

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

If Array contains only one element Then Return

Array

Else

Middle= ((Last + First)/2) rounded down to the nearest integer

LeftHalfArray = MergeSort(Array(First..Middle)) RightHalfArray =

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

Objective: Implementation of Stack ADT algorithm.

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:

A stack is represented in the following way:

Working of the Algorithm:

 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:

IF TOP = MAX then

Print “Stack is full”;

Exit;

Otherwise

TOP = TOP + 1; /*increment TOP*/

STACK (TOP) = ITEM;

End of IF

Exit

Pop Operation:

IF TOP = -1 then

Print “Stack is empty”;

Exit;

Otherwise

7
SEMESTER 3

ITEM =STACK (TOP);

TOP=TOP – 1;

End of IF

Exit

Stack is full:

IF TOP = MAX then

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.

2. Deletion from stack.

3. Check the size of stack.

4. Check the elements of the stack.

5. Exit.

8
SEMESTER 3

Code:

9
SEMESTER 3

Output:

2
SEMESTER 3

LAB # 12

Objective Demonstrate your understanding of Queue ADT by implementing its algorithm.

Theory:

Queue ADT:

 Queue is an abstract data structure, somewhat similar to Stacks.


 It is type of linear data structure.
 It follows FIFO (First-In-First-Out) property.
 A real-world example of queue can be a single-lane one-way road, where the vehicle enters
first, exits first.
 Unlike stacks, a queue is open at both its ends. One end is always used to insert data
(enqueue) and the other is used to remove data (dequeue).
 The two operations are performed on a stack. ENQUEUE & DEQUEUE.
 When inserting an item in a stack, this is called ENQUEUE operation.
 When removing an item from stack, this is called DEQUEUE operation.
 There are two parts of a queue ADT the Rear and Front. REAR part (also called tail) is for
inserting the element in a queue. FRONT part (also called head) is for the removal of existing
element.
 peek( ) function is oftenly used to return the value of first element without dequeuing it.
 If the queue is empty and DEQUEUE operation is applied, it gives an error of Queue Under
Flow.
 If the queue is full or reaches the MAX SIZE and ENQUEUE operation is applied, it gives an
error of Queue Over Flow.

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()

begin procedure peek

return queue[front]

end procedure

 IS FULL()

begin procedure isfull

if rear equals to MAXSIZE

return true

else

return false

endif

end procedure

 IS EMPTY()

begin procedure isempty

if front is less than MIN OR front is greater than rear

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.

• Following operations must be performed.

1. Insertion in Queue.

2. Deletion from queue.

3. Check the size of queue.

4. Check the elements of the queue.

5. Check the peek value of 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.

Linked list is a dynamic data structure.

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 Representation:

Linked list can be visualized as a chain of nodes, where every node points to the next node.

Working:

1. Linked List contains a link element called first.

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:

1. Insertion − Adds an element at the beginning of the list.

2. Deletion − Deletes an element at the beginning of the list.

10
SEMESTER 3

3. Display − Displays the complete list.

4. Search − Searches an element using the given key.

5. Delete − Deletes an element using the given key.


Algorithm:

Creating a linked list.

first=new node;{create the 1st node of the list pointed by first};

Read(Data(first));

NEXT(First)=NULL;

Far a First; [point Far to the First] For

I=1 to N-1 repeat steps 6 to 10.

X=new node;

Read(Data(X))

NEXT(X)=NULL;

NEXT(Far)=X; {connect the nodes}

Far=X;[shift the pointer to the last node of the list] [end of

For Loop]

END

Display:

If First=NULL then {print “List empty” STOP};

count=0;

ptr=First; {point ptr to the 1st node}

While ptr<> NULL repeat Steps 5 to 6

count=count+1;

ptr=NEXT(ptr) [shift ptr to the next node]

print (‘Number of nodes=’, count)

END

11
SEMESTER 3

Searching:

If first=NULL then{

Print “List empty”; STOP;}

ptr=First; [point ptr to the 1st node]

while (ptr<>NULL) repeat steps 4 to 5 If

(DATA (ptr)= ‘X’)

Then {print “item found”;

STOP

ptr=NEXT (ptr); [shift ptr to the next node]

[end of while]

Print “item not found”;

END

Insert at the start of Linked list:

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

Insert after a node:

Ptr=List;

While (ptr<>NULL) repeat steps 3 to 4

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.

Insert before a node:

ptr=LIST

[check if the first node is the desired one]

If(data(ptr)=’VAL’) then

X=new node;

Read DATA(X);

NEXT(X)=LIST;

LIST=X;

STOP;

While(ptr<>NULL ) repeat step 4 to 6

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 of while loop]

END

Deleting a node from a Linked List:

If (DATA(list)=’VAL’)then

Ptr=LIST;

LIST=NEXT(list);

Delete ptr;

Stop;

Back=list;

Ptr=list;

while(ptr<>NULL) repeat step 3 to 5

If(DATA(ptr)=’VAL’) then

NEXT(back)=NEXT(ptr);

Delete ptr;

14
SEMESTER 3

Exit;}

back=ptr;

ptr=next(ptr);

[end of while loop]

END

Task:

Implement the Linked list data structure. Following operations must be performed.

1. Insertion in Linked list.

2. Deletion from Linked list.

3. Check the elements of the Linked list.

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:

Space(A) = Fixed Components(A) + Variable Components(A)

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:

1. Determine the variables which are instantiated by some default values.


2. Determine which instance characteristics should be used to measure the space
requirement and this is will be problem specific.
3. Generally the choices are limited to quantities related to the number and magnitudes of the
inputs to and outputs from the algorithms.

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.

Calculate space complexity:

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:

// n is the length of array a[] int

sum(int a[], int n)

18
SEMESTER 3

int x = 0; // 4 bytes for x

for(int i = 0; i < n; i++) // 4 bytes for i

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;

for count = 1 to size do \\will repeat from 1,2,3,4,........size times

result= result + number[count]; return

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:

• Characteristics of compiler used to compile the program.

• Computer Machine on which the program is executed and physically clocked.

• Multiuser execution system.

• Number of program steps.

Time complexity calculation rules:

• Comments count as zero steps.

• 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.

Time complexity and asymptotic notations:

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.

Constant, n and n2:

• Asymptotic analysis is input bound i.e., if there's no input to the algorithm, it is


concluded to work in a constant time. Other than the "input" all other factors are
considered constant.

• 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.

Usually, the time required by an algorithm falls under three types:

• Best Case − Minimum time required for program execution.

• Average Case − Average time required for program execution.

• Worst Case − Maximum time required for program execution.

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.

For example, for a function f(n)

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:

Always look for the worst case complexity:

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.

Common Asymptotic Notations:

Following is a list of some common asymptotic notations.

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.

n^2 -> O(n2).

O(log n):

1, n and n2 is easy to understand and analyze but what is 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

Selecting the middle element as pivot (length / 2)

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

Similarly, for n elements,

Generalization

Separating the power for the numerator and denominator

Multiplying both sides by 2^k

Final result

Now, let us look at the definition of logarithm, it says that:

A quantity representing the power to which a fixed number (the base) must be raised to
produce a given number.

Which makes our equation into

Logarithmic form

4
SEMESTER 3

Time and Space Complexity of searching and sorting algorithms:

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.

1) Linear Search Algorithm (Time Complexity):

Pseudocode: FUNCTION linearSearch(list, searchTerm): FOR


index FROM 0 -> length(list):
IF list[index] == searchTerm THEN RETURN
index
ENDIF
ENDLOOP
RETURN -1
ENDFUNCTION

2) Selection sort (Time complexity):

Pseudocode: FUNCTION selectionSort(array a)


FOR i in 0 -> a.length - 2
DO
maxIndex = i
FOR j in (i + 1) -> (a.length - 1) DO IF
a[j] > a[maxIndex] THEN maxIndex =
j
swap(a[i], a[maxIndex])
ENDIF
ENDLOOP

5
SEMESTER 3

ENDLOOP
ENDFUNCTION
1) Matrix Addition (Space Complexity):

void matrixAdd(int a[], int b[], int c[], int n) { for


(int i = 0; i < n; ++i) {
c[i] = a[i] + b[j]
}
}

2) Matrix Multiply (Space Complexity):


void matrixMultiply(int a[], int b[], int c[][], int n) { for

(int i = 0; i < n; ++i) {

for (int j = 0; j < n; ++j) { c[i]

= 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:

Tree Data structure:

• Tree represents the nodes connected by edges.

• Trees are well-known as a non-linear data structure. They don’t store data in a linear
way. They organize data hierarchically.

• A tree is a collection of entities called nodes.

• Nodes are connected by edges.

• 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.

Height and Depth of a tree:

• The height of a tree is the length of the longest path to a leaf.

• The depth of a node is the length of the path to its root.

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

Terms related to Binary tree:

• 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.

• Subtree − Subtree represents the descendants of a node.

• Visiting − Visiting refers to checking the value of a node when control is on the node.

• Traversing − Traversing means passing through nodes in a specific order.

• Levels − 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.

• keys − Key represents a value of a node based on which a search operation is to be


carried out for a node.

Binary Tree and Binary Search Tree:

“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 Representation:

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.

BST Basic Operations:

 Insert − Inserts an element in a tree/create a tree.


 Search − Searches an element in a tree.
 Deletion − Delete an element in a tree.
 Preorder Traversal − Traverses a tree in a pre-order manner.
 In order Traversal − Traverses a tree in an in-order manner.
 Post order Traversal − Traverses a tree in a post-order manner.

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

(data < node->data)

node->left = insert(node->left, data); else

if (data > node->data)

node->right = insert(node->right, data);

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.

Pre order Traversal:

 Visit root node


 Visit all the nodes in the left subtree
 Visit all the nodes in the right subtree

display(root->data)

preorder(root->left)

preorder(root->right)

In order Traversal:

 First, visit all the nodes in the left subtree.


 Then the root node.
 Visit all the nodes in the right subtree.

inorder(root->left)

display(root->data)

inorder(root->right)

Post order Traversal:

 Visit all the nodes in the left subtree


 Visit the root node
 Visit all the nodes in the right subtree

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.

• If the node has both left and right child,

1. find the smallest node in the right subtree. say min

2. make node->data = min

3. Again delete the min node.


if(root == NULL)

return NULL;

if(root->key < val)

root->right = removeNode(root->right,val); else

if(root->key > val)

root->left = removeNode(root->left,val);

Else

if(root->left == NULL && root->right == NULL) free(root);

return NULL;

else if(root->left == NULL)

struct node *temp = root->right;

free(root);

return temp;

else if(root->right == NULL) struct

node *temp = root->left;

free(root);

return temp;

else

int rightMin = getRightMin(root->right);

11
SEMESTER 3

root->key = rightMin;

root->right = removeNode(root->right,rightMin);

Task:

Implement a Binary search Tree with the following operations:

 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

You might also like