Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Cs3401_algorithm Lab Record

Uploaded by

saranya.cse
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Cs3401_algorithm Lab Record

Uploaded by

saranya.cse
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

LABORATORY RECORD

CS3401– ALGORITHM LABORATORY


of
B. E. COMPUTER SCIENCE AND ENGINEERING

(Anna University Regulation 2021)

For the Batch (2022 to 2026)


Semester IV
Academic year-2023-2024

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

KCG COLLEGE OF TECHNOLOGY

CHENNAI – 600 097


KARAPAKKAM, CHENNAI 600 097

REG.No. ………………………………

LABORATORY RECORD
Course Code: CS3401

Name of the Course: ALGORITHM LABORATORY

It is to certify that this is a bonafide record of the work carried out

by………..…………..……………………………………………of………………..

semester …………..…………...department, during the Even semester of the


academic

year 2023 -2024.

Faculty In-charge: ………………………… HOD ………………………………….

Internal Examiner: ………………………... External Examiner ………………….

Date of the Examination: ……………………


VISION OF THE COLLEGE

KCG College of Technology aspires to become a globally recognized centre of excellence for
science, technology & engineering education, committed to quality teaching, learning, and
research while ensuring for every student a unique educational experience which will promote
leadership, job creation, social commitment and service to nation-building

MISSION OF THE COLLEGE


 Disseminate knowledge in a rigorous and intellectually stimulating environment

 Facilitate socially responsive research, innovation and entrepreneurship

 Foster holistic development and professional competency

 Nurture the virtue of service and an ethical value system in the young minds

VISION OF THE DEPARTMENT


The department of Computer Science and Engineering desires to become a prominent centre of
excellence for producing competent IT professionals for providing software and software
enabled solutions

MISSION OF THE DEPARTMENT


 Provide quality education in the field of computer science and engineering and related domains
 Facilitate socially responsive research and innovation
 Inculcate professional behavior, a spirit of entrepreneurship and commitment to the progress of
the nation
 Accommodate evolving software development tools and required implementation facilities
PROGRAMME OUTCOMES
After successful completion of B.E COMPUTER SCIENCE & ENGINEERING, the students will be able
to:
PO
No.
Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO 1 fundamentals, and an engineering specialization for the solution of complex engineering
problems.
Problem analysis: Identity, formulate, research literature, and analyze complex
PO 2 engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet t h e specified needs with
PO 3
appropriate consideration for public health and safety, and cultural, societal, and
environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and
PO 4 research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
PO 5 modern engineering and IT tools, including prediction and modeling to complex
engineering activities with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to
PO 6 assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering
PO 7 solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities
PO 8
and norms of the engineering practice.
Individual and teamwork: Function effectively as an individual, and as a member or
PO 9
leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
engineering community and with the society at large, such as being able to comprehend
PO 10
and write effective reports and design documentation, make effective presentations, and
give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the
PO 11 engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to
PO 12 engage in independent and life-long learning in the broadest context of technological
change.
PROGRAMME SPECIFIC OUTCOMES
After successful completion of B.E COMPUTER SCIENCE & ENGINEERING, the students will be able to:

PSO
No.

Apply knowledge pertaining to software engineering principles, computer hardware and


PSO 1 architecture, principles of algorithms & programming skills to analyze complex problems in
computer science engineering and related domains.

Use compiler tool, CASE tool, graphic tool, app development tools, network simulator,
PSO 2 security and analysis tools, cloud and grid tool kits, database management tools, web
development frameworks for providing appropriate solutions.

PSO 3 Demonstrate professional & ethical behavior while providing IT based solutions.

PROGRAMME EDUCATIONAL OBJECTIVES

The graduates of B.E COMPUTER SCIENCE & ENGINEERING will

PEO
Description of PEO
No.

Have successful career as software professional (or) entrepreneur (or) researcher in compute
PEO1
science and relevant disciplines.

Analyze, design, develop, test and deploy appropriate solutions for real world computing
PEO2
problems.

PEO3 Apply software engineering principles at process, project and product levels.

PEO4 Exhibit ethical attitude and social responsibility in their profession.


COURSE OUTCOMES

After the completion of this course, the student will be able to:

CO Blooms
Description of the Course Outcome
No level

CO 1 Explain recursive and non-recursive algorithms and basics of algorithmic K2


problem-solving framework.

CO 2 K3
Analyze the efficiency of algorithms using various frameworks

CO 3 Apply graph algorithms to solve problems and analyze their efficiency. K3

Make use of algorithm design techniques like divide and conquer, dynamic
CO 4 K3
programming, and greedy techniques to solve problems.

CO 5 K3
Apply State Space Tree Analysis to Problem-Solving.

CO 6 K3
Solve problems using approximation algorithms and randomized algorithms
ANNA UNIVERSITY
REGULATIONS 2021
PRACTICAL EXERCISES

Implement Linear Search. Determine the time required to search for an element. Repeat the
experiment for different values of n, the number of elements in the list to be searched and
plot a graph of the time taken versus n.

Implement recursive Binary Search. Determine the time required to search an element.
Repeat the experiment for different values of n, the number of elements in the list to be
searched and plot a graph of the time taken versus n.

Given a text txt [0...n-1] and a pattern pat [0...m-1], write a function search (char pat [ ],
char txt [ ]) that prints all occurrences of pat [ ] in txt [ ]. You may assume that n > m.
Develop a program to implement Heap sort with graph.

Develop a program to implement graph traversal using Breadth First Search


Develop a program to implement graph traversal using Depth First Search
From a given vertex in a weighted connected graph, develop a program to find the shortest
paths to other vertices using Dijkstra’s algorithm.

Find the minimum cost spanning tree of a given undirected graph using Prim’s algorithm.
Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.

Compute the transitive closure of a given directed graph using Warshall's algorithm.

Develop a program to find out the maximum and minimum numbers in a given list of n.
Implement Merge sort and Quick sort methods to sort an array of elements and determine
the time required to sort.
Implement N Queens problem using Backtracking.
Implement any scheme to find the optimal solution for the Traveling Salesperson problem
and then solve the same problem instance using any approximation algorithm and determine
the error in the approximation.

Software Tools
Turbo C
CS3401 ALGORITHMS LABORATORY

Index
Expt
Date Name of the Experiment Page No. Marks Signature
No.

1 Implement Linear Search and Binary Search

2 Pattern Searching

3 Insertion Sort and Heap sort


Develop a program to implement graph traversal using
4 Breadth First Search.
Develop a program to implement graph traversal using
5 Depth First Search
shortest paths to other vertices using Dijkstra’s
6 algorithm.

7 Prim’s algorithm.

8 Floyd’s algorithm
Compute the transitive closure of a given directed
9 graph using Warshall's algorithm.
Implement Merge sort and Quick sort methods to sort
10 an array of elements

11 Implement N Queens problem using Backtracking.

12 Traveling Salesperson problem

13 finding the kth smallest number


Content beyond the Syllabus

Installation of guest operating system - Parrot os


using VMware.
Ex No: 1 IMPLEMENT LINEAR SEARCH AND BINARY SEARCH
Date:

AIM:

To implement Linear search and Binary search and determine the time required to
search for an element

ALGORITHM:
Binary Search

Step 1: if (low > high) then return -1


Step 2: if (low < high) the mid=(low + high)/2
Step 3: X be a key. If a[mid] = X then return mid
Step 4: If a[mid] > X then search for X from a[low] to a[mid-1]
Step 5: If a[mid] < X then search for X from a[mid + 1] to a[high]

Linear Search

Set i to 0.
If Li = T, the search terminates successfully; return i.
Increase i by 1.
If i < n, go to step 2. Otherwise, the search terminates unsuccessfully.

PROGRAM
OUTPUT

Result
Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS

1.How does a linear search work in data structures?

2.When should you use linear search instead of binary search?

3. If we have two arrays, one sorted and the other unsorted, which one would you
recommend for implementing a linear search?

4. In what ways does multi-threading help improve the performance of a linear search?
Ex No: 2 PATTERN SEARCHING
Date:

AIM:
To write a C program for a given text and pattern and write a search function
that prints all occurrences of pattern in text.

ALGORITHM:

Algorithm-NAVE_STRING_MATCHING (T, P)
for i←0 to n-m do
if P[1......m] == T[i+1.....i+m] then
print "Match Found"
end
end

PROGRAM:
OUTPUT:

RESULT:

Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS:
1. How pattern matching different from substring searching?

2. How would you use pattern matching in a real-time system?

3.How will you measure input size of algorithms?

4. How would you use pattern matching in a data analysis scenario?


Ex No: 3 HEAP SORT
Date:

AIM:

To Implement Heap sort methods and determine the time required to sort the elements..

ALGORITHM:

The Heap sort algorithm to arrange a list of elements in ascending order is performed using
following steps...
Step 1 - Construct a Binary Tree with given list of Elements.
Step 2 - Transform the Binary Tree into Min Heap.
Step 3 - Delete the root element from Min Heap using Heapify method.
Step 4 - Put the deleted element into the Sorted list.
Step 5 - Repeat the same until Min Heap becomes empty.
Step 6 - Display the sorted lis

PROGRAM:
Output

RESULT:

Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS

1.Differentiate heap and a stack.Which is better?

2. How does heapsort work?

3. Is it possible to sort an array using Heapsort without building a heap? If yes, then how?

4. Why isn’t a binary tree used for implementing heaps instead of arrays?
Ex No: 4 BREADTH FIRST SEARCH
Date:

AIM:

To implement a graph traversal program using Breadth First Search.

ALGORITHM

Step 1: Take an Empty Queue.

Step 2: Select a starting node (visiting a node) and insert it into the Queue.

Step 3: Provided that the Queue is not empty, extract the node from the Queue and
insert its child nodes (exploring a node) into the Queue.

Step 4: Print the extracted node.

PROGRAM
OUTPUT
RESULT:

Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS:

1. How Does BFS Work?

2.Is BFS a stack or queue?. Justify.

3.Differentiate BFS and DFS.

4. Is breadth-first search a backtracking algorithm? Justify.


x No: EX.NO :5 DEPTH FIRST SEARCH

Date:

AIM:

To implement a program graph traversal using Depth First Search.

ALGORITHM

Step 1: Select the start node.

Step 2: Visit the start node.

Step 3: Explore the neighbours of the start node.

Step 4: If there are undiscovered neighbour nodes, switch to that node and repeat the steps
(recursively or using a chunk data structure).

Step 5: When there are no undiscovered neighbour nodes, go back and return to the previous
node.

Step 6: Repeat the steps until all nodes have been visited.

PROGRAM
OUTPUT

RESULT
Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS

1.Differenciate Compile and Running Time.

2.How Does DFS Work? Justify.

3.If the depth of a tree is 3 levels, then what is the size of the Tree ?

4.Differentiate Tree and Graph.


Ex No: 6 DIJKSTRA’S ALGORITHM
Date:

AIM
To form a given vertex in a weighted connected graph and to find shortest paths to other vertices using Dijkstra’s
algorithm.

ALGORITHM

Create a shortest path tree set that keeps track of vertices included in shortest path tree,
i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty.
- Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE.
- Assign distance value as 0 for the source vertex so that it is picked first.
- While shortest path tree set doesn’t include all vertices
a) Pick a vertex u which is not there in shortest path tree set and has minimum distance value.
b) Include u to shortest path tree set
c) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertice
For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance
value of v, then update the distance value of v.

PROGRAM
OUTPUT

RESULT

Evaluation by Faculty Members: Particulars Marks


Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)
Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS

1. Differentiate Time And Space Complexity..

2.Where you would use Dijkstra’s algorithm?.

3. Differenciate Prims and Kruskal’s algorithm.


4. Is it possible to use Dijkstra’s algorithm for directed graphs? Justify.
Ex No: 7 PRIMS'S ALGORITHM
Date:

AIM:
To find the minimum spanning tree of given undirected graph using prims's algorithm.
ALGORITHM
Step 1: start the program
Step 2: Initialize the algorithm by choosing the
source vertex.
Step 3:Find the minimum weight edge connected to
the source node and another node and add
it to the tree.
Step 4:Keep repeating this process until we find minimum spanning tree. To write a shell
program to
find the sum of n numbers.

PROGRAM
OUTPUT
RESULT

Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks…………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS

1. Differentiate weighted and unweighted graphs.

2. Why is it important for us to know about minimum-spanning trees in the context of


data science?

3. How do you find the weight of an edge in a minimum spanning tree?

4. How does Prim's algorithm find a spanning tree?


Ex No: 8 FLOYDS ALGORITHM
Date:

AIM:

Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.


ALGORITHM:

For a graph with N vertices:

Step 1: Initialize the shortest paths between any 2 vertices with Infinity.

Step 2: Find all pair shortest paths that use 0 intermediate vertices, then find the shortest paths
that use 1 intermediate vertex and so on.. until using all N vertices as intermediate nodes.

Step 3: Minimize the shortest paths between any 2 pairs in the previous operation.

Step 4: For any 2 vertices (i,j) , one should actually minimize the distances between this pair
using the first K nodes, so the shortest path will be: min(dist[i][k]+dist[k][j],dist[i][j]).

dist[i][k] represents the shortest path that only uses the first K vertices, dist[k][j] represents the
shortest path between the pair k,j. As the shortest path will be a concatenation of the shortest
path from i to k, then from k to j.

PROGRAM:
OUTPUT

Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS:

1.Which are Approaches being followed in Floyd’s Warshalls algorithm?

2.Which algorithms are used to find the shortest path from a source node to all other nodes in a
weighted graph?

3.Describe the consideration points when designing an algorithm

4.What is the best time complexity we can achieve to precompute all-pairs shortest paths in a
weighted graph?
Ex No: 9 TRANSITIVE CLOSURE OF A GIVEN DIRECTED GRAPH USING
WARSHALL'S ALGORITHM
Date:

AIM:

To compute the transitive closure of a given directed graph using Warshall’s


algorithm.

ALGORITHM:
path exists between two vertices i, j,
• there is an edge from i to j; or
• there is a path from i to j going through vertex 1; or
• there is a path from i to j going through vertex 1 and/or 2; or
• there is a path from i to j going through vertex 1, 2, and/or 3; or
• there is a path from i to j going through any of the other vertices 3 3 3
Recurrence relating elements R(k) to elements of
R(k-1) is: R(k) [i,j] = R(k-1)[i,j] or (R(k-1)[i,k] and R(k-1)[k,j])
It implies the following rules for generating R(k) from R(k-1):

Rule 1 If an element in row i and column j is 1 in R(k-1) , it remains 1 in R(k)

Rule 2 If an element in row i and column j is 0 in R(k-1) , it has to be changed to 1 in R(k)


it has to be changed to 1 in R if and only if (k) if and only if the element in its row i and
column k and the element in its column j and row k are both 1’s in R(k-1)

PROGRAM:
OUTPUT:

RESULT:

Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS:

1. How does the Floyds algorithm work for a negative edge graph?

2.Examples of divide and conquer algorithms?

3.How many spanning trees can a graph has?

4.How to work brute force approach?


Ex No: 10 QUICK SORT
Date:

Aim
To sort an array of N numbers using Quick sort.

Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Select an pivot element x from Ai
5. Divide the array into 3 sequences: elements < x, x, elements > x
6. Recursively quick sort both sets (Ai < x and Ai > x)
7. Stop
PROGRAM
OUTPUT:

RESULT

Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS

1. Is it possible to Quick Sort suitable for use on large datasets? Why or why not?

2. Mention the various types of searching techniques in C.

3. How does the Quick Sort work?

4. How many elements can be sorted using Quick Sort?


Ex No: 11 IMPLEMENTATION OF N QUEENS PROBLEM USING
Date: BACKTRACKING

AIM

To solve N Queens problem using backtracking

ALGORITHM

Step 1 - Place the queen row-wise, starting from the left-most cell.

Step 2 - If all queens are placed then return true and print the solution matrix.

Step 3 - Else try all columns in the current row.

Condition 1 - Check if the queen can be placed safely in this column then mark the
current cell [Row, Column] in the solution matrix as 1 and try to check the rest of the problem
recursively by placing the queen here leads to a solution or not.

Condition 2 - If placing the queen [Row, Column] can lead to the solution return true and
print the solution for each queen's position.

Condition 3 - If placing the queen cannot lead to the solution then unmark this [row,
column] in the solution matrix as 0, BACKTRACK, and go back to condition 1 to try other rows.

Step 4 - If all the rows have been tried and nothing worked, return false to trigger backtracking.

PROGRAM
OUTPUT:

RESULT
Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
Review Questions
1. How would you use a backtracking algorithm to solve a constraint-satisfaction
problem?

2. How can you apply memorization techniques to optimize backtracking algorithms?

3. Differentiate Branch and bound and greedy method.

4. How would you implement backtracking algorithms in a parallel computing


environment?
Ex No: 12 TRAVELLING SALESMAN PROBLEM
Date:

AIM:
To Implement any scheme to find the optimal solution for the Traveling Salesperson
problem and then solve the same problem instance using any approximation algorithm and
determine the error in the approximation.

ALGORITHM:
Step1: start the program.

Step2: First of all, we have to create two primary data holders.

o First of them is a list that can hold the indices of the cities in terms of the input
matrix of distances between cities
o And the Second one is the array which is our result

Step3: Perform traversal on the given adjacency matrix tsp[][] for all the city and if the cost of
reaching any city from the current city is less than the current cost the update the cost.

Step4: Generate the minimum path cycle using the above step and return their minimum cost.

Step5: stop the program.

PROGRAM
OUTPUT
RESULT:

Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS

1. Which method is used in the traveling salesman problem?

2,Which data structure is used in travelling salesman problem?

3.How do you solve travelling salesman problem?

4. Is it possible travelling salesman problem be solved using greedy method?


Ex No: 13 FINDING THE KTH SMALLEST NUMBER
Date:

AIM:

To implement randomized algorithms for finding the kth smallest number .

ALGORITHM:

1. Take the input of the data set.


2. Take the input of the value of k.
3. Call Partition().
4. Inside Partition(), rearrange the array according to the pivot using
CreatePartition()
5. Get the new index of the pivot as ‘pindex’ and compare it with (k-1).
6. If both the values are equal then return the value as a result to the main().
7. If pindex > k-1, recursively call Partition() for the part before the pivot
value.
8. If pindex < k-1, recursively call Partition() for the part after the pivot value.

9. Inside main(), print the kth smallest element.

10. Exit

PROGRAM:
OUTPUT

RESULT:
Evaluation by Faculty Members:

Particulars Marks
Program/Execution (7)
Output &Results(3)
Viva (10)
Total (20)

Faculty Remarks……………………………………………………………………...

Faculty Signature
REVIEW QUESTIONS:

1.Which problem is solved by greedy method?

2.How to find kth smallest element in array in C?

3. Differentiate KTH largest and smallest element.

4. How to find Kth Smallest Element in a Binary Search Tree?

You might also like