DesignandAnalysisofAlgorithms - LabManual - 2021scheme Ay2022 2023 2021batch
DesignandAnalysisofAlgorithms - LabManual - 2021scheme Ay2022 2023 2021batch
LAB MANUAL
2022-2023
IV SEMESTER CSE
These are sample Strategies, which teachers can use to accelerate the attainment of the various course
outcomes.
1. Lecturer method (L) does not mean only traditional lecture method, but different type of
teaching methods may be adopted to develop the outcomes.
2. Show Video/animation films to explain functioning of various concepts.
3. Encourage collaborative (Group Learning) Learning in the class.
4. Ask at least three HOT (Higher order Thinking) questions in the class, which promotes critical
thinking.
5. Adopt Problem Based Learning (PBL), which fosters students’ Analytical skills, develop thinking
skills such as the ability to evaluate, generalize, and analyze information rather than simply recall
it.
6. Topics will be introduced in a multiple representation.
7. Show the different ways to solve the same problem and encourage the students to come up with
their own creative ways to solve them.
8. Discuss how every concept can be applied to the real world - and when that's possible, it helps
improve the students' understanding.
Module-1
Laboratory Component:
1. Sort a given set of n integer elements using Selection Sort method and compute its time complexity.
Run the program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the
time taken versus n. The elements can be read from a file or can be generated using the random
number generator. Demonstrate using C++/Java how the brute force method works along with its
time complexity analysis: worst case, average case and best case.
Laboratory Component:
1. Sort a given set of n integer elements using Quick Sort method and compute its time complexity. Run
the program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the time
taken versus n. The elements can be read from a file or can be generated using the random number
generator. Demonstrate using C++/Java how the divide-and-conquer method works along with its
time complexity analysis: worst case, average case and best case.
2. Sort a given set of n integer elements using Merge Sort method and compute its time complexity.
Run the program for varied values of n> 5000, and record the time taken to sort. Plot a graph of the
time taken versus n. The elements can be read from a file or can be generated using the random
number generator. Demonstrate using C++/Java how the divide-and-conquer method works along
with its time complexity analysis: worst case, average case and best case.
Teaching-Learning Process 1. Chalk & board, Active Learning, MOOC, Problem based
Learning.
2. Laboratory Demonstration.
Module-3
Minimum cost spanning trees: Prim’s Algorithm, Kruskal’s Algorithm with performance analysis.
Laboratory Component:
Dynamic Programming: All Pairs Shortest Paths: Floyd's Algorithm, Knapsack problem,
Module-5
1. Design and implement C++/Java Program to find a subset of a given set S = {Sl, S2,…, Sn} of n
positive integers whose SUM is equal to a given positive integer d. For example, if S = {1, 2, 5, 6, 8}
and d= 9, there are two solutions {1, 2, 6} and {1, 8}. Display a suitable message, if the given
problem instance doesn't have a solution.
2. Design and implement C++/Java Program to find all Hamiltonian Cycles in a connected undirected
Graph G of n vertices using backtracking principle.
Teaching-Learning Process 1. Chalk & board, Active Learning, MOOC, Problem based
learning.
2. Laboratory Demonstration.
Course outcome (Course Skill Set)
CO 1. Analyze the performance of the algorithms, state the efficiency using asymptotic notations andanalyze
mathematically the complexity of the algorithm.
CO 2. Apply divide and conquer approaches and decrease and conquer approaches in solving the
problems analyze the same
CO 3. Apply the appropriate algorithmic design technique like greedy method, transform and conquer
approaches and compare the efficiency of algorithms to solve the given problem.
CO 4. Apply and analyze dynamic programming approaches to solve some problems. and improve an
algorithm time efficiency by sacrificing space.
CO 5. Apply and analyze backtracking, branch and bound methods and to describe P, NP and NP-
Complete problems.
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%. The
minimum passing mark for the CIE is 40% of the maximum marks (20 marks). A student shall be deemed to
have satisfied the academic requirements and earned the credits allotted to each subject/ course if the student
secures not less than 35% (18 Marks out of 50) in the semester-end examination (SEE), and a minimum of
40% (40 marks out of 100) in the sum total of the CIE (Continuous Internal Evaluation) and SEE (Semester
End Examination) taken together
Practical Sessions need to be assessed by appropriate rubrics and viva-voce method. This will contribute to 20
marks.
Rubrics for each Experiment taken average for all Lab components – 15 Marks.
The sum of three tests, two assignments, and practical sessions will be out of 100 marks and will be
scaled down to 50 marks
(to have a less stressed CIE, the portion of the syllabus should not be common /repeated for any of the
methods of the CIE. Each method of CIE should have a different syllabus portion of the course).
CIE methods /question paper has to be designed to attain the different levels of Bloom’s taxonomy as
per the outcome defined for the course.
Theory SEE will be conducted by University as per the scheduled timetable, with common question papers
for the subject (duration 03 hours)
1. The question paper will have ten questions. Each question is set for 20 marks. Marks scored shall
be proportionally reduced to 50 marks
2. There will be 2 questions from each module. Each of the two questions under a module (with a
maximum of 3 sub-questions), should have a mix of topics under that module.
The students have to answer 5 full questions, selecting one full question from each module
1. Real world problem solving and puzzles using group discussion. E.g., Fake coin identification,
Peasant, wolf, goat, cabbage puzzle, Konigsberg bridge puzzle etc.,
2. Demonstration of solution to a problem through programming.
Eclipse for Java: How To Install Eclipse and Get Started wit h Java Programming
on Windows
Eclipse (@ www.eclipse.org) is an open-source Integrated Development Environment (IDE)
supported by IBM. Eclipse is popular for Java application development (Java SE and Java EE)
and Android apps. It also supports C/C++, PHP, Python, Perl, and other web project
developments via extensible plug-ins. Eclipse is cross-platform and runs under Windows, Linux
and macOS.
Eclipse Versions
There are various versions of eclipse from Eclipse 1.0 to Eclipse 2019-12 (4.14).
https://www3.ntu.edu.sg/home/ehchua/programming/howto/EclipseJava_HowTo.html
Video
https://www.youtube.com/watch?v=WIzzHeWukUU
5: select Windows x64 Compressed Archive in the list i.e click jdk-13.0.2_windows-
x64_bin.zip [178.99 MB]
Step 1: Download
Download Eclipse from https://www.eclipse.org/downloads. Under "Get Eclipse IDE 2019-12"
⇒ Click "Download s". For beginners, choose the "Eclipse IDE for Java Developers" and
"Windows 64-bit" (e.g., "eclipse-java-2019-12-R-win32-x86_64.zip" - about 201MB) ⇒
Download.
Step 2: Unzip
To install Eclipse, simply unzip the downloaded file into a directory of your choice (e.g.,
"c:\myProject").
The zip version is preferred because there is no need to run any installer. Moreover, you can
simply delete the entire Eclipse directory when it is no longer needed (without running any un-
installer). You are free to move or rename the directory. You can install (unzip) multiple copies
of Eclipse in the same machine.
3. If the "Welcome" screen shows up, close it by clicking the "close" button next to the
"Welcome" title.
1. Choose "File" menu ⇒ "New" ⇒ "Java project" (or "File" ⇒ "New" ⇒ "Project" ⇒ "Java
project").
c. In "JRE", select "Use default JRE (currently 'JDK11.0.x')". But make sure that your
JDK is 1.8 and above.
d. In "Project Layout", check "Use project folder as root for sources and class files".
System.out.println("Hello, world!");
}
}
3. The output "Hello, world!" appears on the Console panel (the bottom pane).
NOTES:
You should create a NEW Java project for EACH of your Java application.
Nonetheless, Eclipse allows you to keep more than one programs in a project, which is
handy for writing toy programs (such as your tutorial exercises). To run a particular
program, open and right-click on the source file ⇒ Run As ⇒ Java Application.
Clicking the "Run" button (with a "Play" icon) runs the recently-run program (based on the
previous configuration). Try clicking on the "down-arrow" besides the "Run" button.
Eclipse performs incremented compilation, as and when a source "line" is entered. It marked a
source line having syntax error with a RED CROSS. Place your cursor at the RED CROSS to
view the error message.
You CANNOT RUN the program if there is any syntax error (marked by a RED CROSS before
the filename). Correct all the syntax errors; and RUN the program.
HINTS: In some cases, Eclipse shows a ORANGE LIGHT-BULB (for HINTS) next to the
ERROR RED-CROSS (Line 5 in the above diagram). You can click on the LIGHT-BULB to get
a list of HINTS to resolve this particular error, which may or may not work!
Able to use a graphics debugger to debug program is crucial in programming. It could save you
countless hours guessing on what went wrong.
"Resume" continues the program execution, up to the next breakpoint, or till the end of the
program.
Alternatively, you can place the cursor on a particular statement, and issue "Run-To-Line" from
the "Run" menu to continue execution up to the line.
"Terminate" ends the debugging session. Always terminate your current debugging session using
"Terminate" or "Resume" till the end of the program.
Click the "Java" perspective icon on the upper-right corner to switch back to the "Java"
perspective for further programming (or "Window" menu ⇒ Open Perspective ⇒ Java).
Important: Mastering the use of debugger is crucial in programming. Explore the features
provided by the debuggers.
Other Debugger's Features
Step-Into and Step-Return: To debug a method, you need to use "Step-Into" to step into
the first statement of the method. ("Step-Over" runs the function in a single step without stepping
through the statements within the function.) You could use "Step-Return" to return back to the
caller, anywhere within the method. Alternatively, you could set a breakpoint inside a method.
Modify the Value of a Variable: You can modify the value of a variable by entering a new
value in the "Variable" panel. This is handy for temporarily modifying the behavior of a
program, without changing the source code.
5. Tips & Tricks
5.1 General Usages (for all Programming Tasks)
o Ctrl-Space: auto-complete.
15. Explorer vs. Navigator: We usually use " Explorer" in programming, but it will not
show you all the folders and files under the project. On the other hand, "Navigator" is a
file manager that shows the exact file structure of the project (similar to Windows
Explorer). You can enable the Navigator by "Window" ⇒ Show view ⇒ Navigator.
16. Spell Check: To enable spell check, select Window ⇒ Preferences ⇒ type "spell" in the
filter ⇒ General ⇒ Editors ⇒ Text Editors ⇒ Spelling ⇒ Check "Enable spell checking".
o To create a new snippet item: Copy the desired text ⇒ Select the snippet category ⇒
paste as snippet.
o To insert a snippet: place the cursor on the desired location at the editor panel ⇒ click
the snippet item.
21. Word Wrap (Line Wrap): Word-wrap (or line-wrap) is essential for editing long
HTML documents without the horizontal scroll bar. However, the Eclipse's HTML Editor
and Text Editor do not support word-wrap.
You could install a plug-in called "Word Wrap" from http://ahtik.com/eclipse-update/.
Choose "Help" ⇒ Install New Software ⇒ in "Work with" Enter "http://ahtik.com/eclipse-
update/".
To activate word wrap, right-click on the editor panel ⇒ select "Word Wrap".
22. Creating "link folder" in project : You do not have to place all the folders under the
project base directory, instead, you can use so-called "link folders" to link to folder outside
the project base directory.
To create a link folder in a project, right-click on the project ⇒ File ⇒ New ⇒ Folder ⇒
Advanced ⇒ Check Link to alternate Location (Linked Folder).
24. Show the Right Margin: Window ⇒ Preferences ⇒ General ⇒ Editors ⇒ Text Editors ⇒
Show Print Margin and set the column number.
All the above options are also accessible via project's property ⇒ "Build Path".
Notes: The JAR files must be included in the CLASSPATH. The native library directories
must be included in JRE's property "java.library.path", which normally but not necessarily
includes all the paths from the PATH environment variable. Read "External JAR files and
Native Libraries".
9. Creating a User Library: You can also create a Eclipse's user library to include a set
of JAR files and native libraries, that can then be added into subsequent Eclipse projects.
For example, I created a user library for "JOGL" as follows:
a. From "Window" menu ⇒ Preferences ⇒ Java ⇒ Build Path ⇒ User Libraries ⇒
New ⇒ In "User library name", enter "jogl". The "User Library" dialog appears.
b. In "User Library" dialog ⇒ Select "jogl" ⇒ Add JAR... ⇒ Navigate
to <JOGL_HOME>/lib, and select "gluegen-rt.jar" and "jogl.jar".
e. You may provide the source files by editing "Source attachment: (none)". Source is
needed only if you are interested to debug into the JOGL source codes.
For EACH subsequent Java project created that uses JOGL, right-click on the project ⇒
Build Path ⇒ Add Libraries ⇒ Select "User Library" ⇒ Check "jogl".
Running an External Program: Suppose that you want to run a Perl script on the
selected file, you can configure an external tool as follows:
b. Choose the "Main" tab ⇒ In "Location", "Browse File System..." to choose the perl
interpreter "perl" ⇒ In "Arguments", enter "path/scriptname.pl ${resource_loc}",
where ${resource_loc} is an Eclipse variable that denotes the currently selected
resource with absolute path.
c. Choose the "Common" tab ⇒ In "Standard Input and Output", uncheck "Allocate
Console", check "File" and provide an output file
(e.g., d:\temp\${resource_name}.txt).
d. (If you use the CYGWIN perl interpreter, need to set environment variable
CYGWIN=nodosfilewarning to disable warning message.)
To run the configured external tool, select a file ⇒ run ⇒ external tool ⇒ tool name.
Viewing Hex Code of Primitive Variables in Debug mode: In debug
perspective, "Variable" panel ⇒ Select the "menu" (inverted triangle) ⇒ Java ⇒ Java
1. Sort a given set of n integer elements using Selection Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to
sort. Plot a graph of the time taken versus n. The elements can be read from a file or can be
generated using the random number generator. Demonstrate using C++/Java how the
brute force method works along with its time complexity analysis: worst case, average case
and best case.
Selection Sort Using Brute Force Method:
Introduction
Sorting data is a frequent problem in computer science. Given a collection of elements, the goal
is to rearrange them in some order. Common examples are sorting an array alphabetically or
from smallest to largest.
Sorted data is a lot easier to manipulate. Finding the largest or smallest element of an array can
be done in constant time if the array is sorted. Searching for an element is a lot faster using
algorithms such as Binary Search which rely on the assumption that the array is already sorted.
Selection Sort
Selection sort is an in-place comparison sorting algorithm that uses brute force to sort an array.
In-place means that the algorithm uses a small constant amount of space for extra storage.
It's called a "brute force" algorithm because it uses the simplest and most ineffective way of
calculating the solution. However, it does makes up for it with its straightforward
implementation.
A sorted subarray
An unsorted subarray
The sorted subarray is empty in the beginning. In every iteration, the smallest element of the
unsorted array will be appended to the end of the sorted array by swapping. This way, the sorted
array will eventually contain all the elements of the original array.
Implementation
The selectionSort() method takes just one argument, the array that needs to be sorted. We'll
iterate through the unsorted array, which will be between indexes i and j, find it's minimum and
place it into the sorted array by swapping:
Pseudocode :
selectionSort(int[] nums)
{
for (int i 0; i < nums.length; i++)
{
// min is the index of the smallest element with an index greater or equal to i
int min i;
for (int j i + 1; j < nums.length; j++)
{
if (nums[j] < nums[min])
{
min j;
}
}
// Swapping i-th and min-th elements
swap nums[i] with nums[min];
}
}
Time complexity is a way to describe how much time an algorithm needs to finish executing
relative to the size of the input. Analyzing the time it takes for an algorithm to give output is of
crucial importance. Imagine a telephone book application that would take a day to sort all the
numbers after a new number was added. That would be way less useful than the same app that
would do it almost instantly.
Performance depends on the hardware as well as software, but the same program can be run on
many different types of hardware. The Big-O notation makes it easier to approximate the time
needed for a program to execute, regardless of software.
The average and worst-case time complexity of Selection Sort is O(n2). This makes Selection
Sort a lot slower than many other comparison sorting algorithms like Merge Sort or Insertion
Sort which have the worst-case time complexity (O(nlogn)). Interestingly, O(nlogn) is the best
that can be achieved by any comparison sorting algorithm.
Showing that Selection Sort has quadratic time complexity comes down to calculating the
number of times the inner loop will be iterated. We can see this if we go through the code line by
line and try to approximate the time it takes to execute each line of code:
Everything in the inner block of the loop will be executed n times, where n is the length of a
given array:
int min= i;
min will be initialized to i exactly n times. Now comes the tricky part:
Since this loop is nested, it takes a bit of math to calculate the number of times the block of code
inside it will execute. Let's work it out.
When i is equal to 0, j will go from 1 to n, meaning every instruction in the inner block will
execute n times. When i increases to 1, j will stay between 2 and n, which implies the inner block
will execute n-2 times. Summing this up:
(n - 1) + (n - 2) + ... + 1
Put simply, when calculating the complexity of an algorithm O(f(n)), we need to look for the
highest power of n in the function f(n) and isolate it. This is because any part of the equation that
has a lower power will not affect the result in any significant way.
For example, we have the function f(x) = x2+13x+23
O(f(x)) would be the highest power of x in the equation, which in this case is x2.
Here's how it performed after sorting an array containing 10,000 integers in random order:
// Shuffle array
Collections.shuffle(Arrays.asList(array));
The average run time was 0.0236 seconds, though; this will majorly depend on your machine as
well.
Space Complexity is also a big factor in algorithm design. Our programs are bound, not only by
the time that they need to execute but also by memory usage. There is a limited amount of
memory on any computer, so a programmer should keep an eye on that too.
The space complexity of Selection Sort is constant(O(1)) because it is in-place, which is great.
Worst case complexity of Selection Sort is, unfortunately, O(n2) as well, which means that even
if the algorithm gets an already sorted array as input, it will still take a lot of time to return the
unchanged array.
This algorithm has decent performance if the collection doesn't have a lot of elements. If the
array has ~10 elements, the difference in performance between different sorting algorithms
shouldn't be that noticeable, and Selection Sort might even outperform other divide-and-conquer
algorithms.
Where Selection Sort shines, is when the number of swaps needs to be minimal. In the worst
case, there will only be n-1 swaps, which is the minimal possible number of swaps that need to
be performed. This is quite intuitive if consider that every element will be placed in its right spot
in the sorted array right away.
Conclusion
Selection Sort is a brute force in-place comparison sort which continuously finds the minimum
of an unsorted subarray and places it in the correct position in the sorted subarray. Due to its
simplicity, it's often one of the first algorithms that are taught in computer science courses all
around the world.
// Shuffle array
Collections.shuffle(Arrays.asList(array));
Output:
Note: For n=5000 to 50000 in step of 5000 note down the time in nanoseconds. Convert time in
seconds and plot the graph with n as x axis and time as y axis.
1. Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to
sort. Plot a graph of the time taken versus n. The elements can be read from a file or can
be generated using the random number generator. Demonstrate using C++/Java how the
divide-and-conquer method works along with its time complexity analysis: worst case,
average case and best case.
Pseudocode : QUICKSORT(a[l..r])
//Sorts a subarray by quicksort
//Input: A subarray A[l..r] of A[0..n-1],defined by its left and right indices l and r
//Output: Subarray A[l..r] sorted in nondecreasing order
{
if l<r
{
s← Partition(A[l..r]) //s is a split position
QUICKSORT(A[l..s-1])
QUICKSORT(A[s+1..r])
}
}
Pseudocode : Partition(A[l..r])
//Partition a subarray by using its first element as its pivot
//Input:A subarray A[l..r] of A[0..n-1],defined by its left and right indices l and r (l<r)
//Output:A partition of A[l..r],with the split position returned as this function’s value
{
p ← A[l]
i ← l; j ← r+1
repeat
{
repeat i ← i+1 until A[i] >=p and i<=high
repeat j ← j-1 until A[j] <=p
swap(A[i],A[j])
} until i>=j
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
33
Design and Analysis of Algorithms -21CS42- Laboratory Component
swap(A[i],A[j]) // undo last swap when i>=j
swap(A[l],A[j])
return j
Program 1
a)The elements generated using the random number generator
import java.util.Random;
import java.util.Scanner;
Output:
Quicksort Test
Enter the number of elements
10
the random elements are
17
31
81
44
91
24
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
36
Design and Analysis of Algorithms -21CS42- Laboratory Component
87
42
57
17
The Elements after sorting
17
17
24
31
42
44
57
81
87
91
Time taken for execution is:6316 nanoseconds
Note: For n=5000 to 50000 in step of 5000 note down the time in nanoseconds. Convert time in
seconds and plot the graph with n as x axis and time as y axis.
Quicksort Test
17
31
81
44
91
24
87
42
57
17
17
17
24
31
42
44
57
81
87
91
Time taken for execution is: 6316 nanoseconds
2. Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program for varied values of n> 5000, and record the time taken to
sort. Plot a graph of the time taken versus n. The elements can be read from a file or can be
generated using the random number generator. Demonstrate using C++/Java how the
divide-and-conquer method works along with its time complexity analysis: worst case,
average case and best case.
Pseudocode : Merge(a,low,mid,high)
//a[low:high] is a global array containing two sorted subsets in a[low:mid] and in a[mid+1:high].
//Merge two sets into a single set in a[low:high],b[] is an auxiliary global array.
{
h<-low
i<-low
j<-mid+1
while h<=mid && j<=high do
{
if a[h]<=a[j] then
{
b[i] <- a[h]
h++
}
else
{
b[i] <- a[j]
Program 2
import java.util.Random;
import java.util.Scanner;
Output:
MergeSort Test
Enter the number of elements
10
the random elements are
71
66
52
97
59
48
84
32
53
54
The Elements After sorting
32
48
52
53
54
59
66
71
84
97
Time taken for execution is:21316 nanoseconds
Note: For n=5000 to 50000 in step of 5000 note down the time in nanoseconds. Convert time in
seconds and plot the graph with n as x axis and time as y axis.
Module 3
1. Write & Execute C++/Java Program to solve Knapsack problem using Greedy method.
Pseudocode: GreedyKnapsack(m,n)
//p[1:n] and w[1:n] – contains the profits and weights of n objects ordered such that
//p[i]/w[i] >= p[I+1]/w[i+1]
//m is size of knapsack and x[1:n] is the solution vector
{
for i<- 1 to n do
x[i]=0.0
u <- m
for i <- 1 to n do
{
if (w[i] > u) then break
x[i] <- 1.0
u <- u-w[i]
}
if (i<=n) then
x[i]=u / w[i]
}
Program 1
import java.util.Scanner;
public class Knapsack
{
public static void knapsack(int n, int item[],float weight[], float profit[], float capacity)
{
float tp = 0,u;
int i;
if (i < n)
x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]);
System.out.println("\nThe result vector is:- ");
for (i = 0; i < n; i++)
System.out.println("\tItem "+item[i]+":" +x[i]);
System.out.println("\nMaximum profit is:- " +tp);
}
public static void main(String[] args)
{
float weight[]=new float[20];
float profit[]=new float[20];
float capacity;
int num, i, j;
float ratio[]=new float[20], temp;
int item[]=new int[10];
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
48
Design and Analysis of Algorithms -21CS42- Laboratory Component
Scanner in=new Scanner(System.in);
System.out.println("\nEnter the no. of objects:- ");
num=in.nextInt();
System.out.println("\nEnter the the items, weights and profits of each object:- ");
for (i = 0; i < num; i++)
{
item[i]=in.nextInt();
weight[i]=in.nextFloat();
profit[i]=in.nextFloat();
}
System.out.println("\nEnter the capacityacity of knapsack:- ");
capacity=in.nextFloat();
for (i = 0; i < num; i++)
{
ratio[i] = profit[i] / weight[i];
}
for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
if (ratio[i] < ratio[j])
{
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
49
Design and Analysis of Algorithms -21CS42- Laboratory Component
profit[j] = profit[i];
profit[i] = temp;
temp=item[j];
item[j]=item[i];
item[i]=(int)temp;
}
}
}
knapsack(num, item,weight, profit, capacity);
}
}
Output:
Enter the no. of objects:-
3
Single Source Shortest Paths Problem using Greedy Method :( Dijkstra’s algorithm )
For a given vertex called the source in a weighted connected graph, find the shortest paths to all
its other vertices. Dijkstra’s algorithm is the best known algorithm for the single source shortest
paths problem. This algorithm is applicable to graphs with nonnegative weights only and finds
the shortest paths to a graph’s vertices in order of their distance from a given source. It finds the
shortest path from the source to a vertex nearest to it, then to a second nearest, and so on. It is
applicable to both undirected and directed graphs
Example: 2
1 2
3 4
Pseudocode:
findmin( )
{
for i ← to n do
if (s[i] = 0) do
{
min ← i
break
}
for i ← 1 to n do
{
if (d[i]<d[min] & s[i]=0)
min ← i
}
return min
}
dijkstra( )
{
for i ← to n do
{
s[i] ← 0
d[i] ← 999
p[i] ← 0
}
d[v] ← 0
for k ← 1 to n do
import java.util.Scanner;
int i,n,min=0;
n=in.nextInt();
for(i=1;i<=n;i++)
if(s[i]==0)
min=i;
break;
for(i=1;i<=n;i++)
min=i;
return min;
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
53
Design and Analysis of Algorithms -21CS42- Laboratory Component
}
int i,w1,u,k,j;
for(i=1;i<=n;i++)
s[i]=0;
d[i]=999;
p[i]=0;
d[v]=0;
for(k=1;k<=n;k++)
u=findmin();
s[u]=1;
for(w1=1;w1<=n;w1++)
if(d[w1]>d[u]+w[u][w1])
d[w1]=d[u]+w[u][w1];
p[w1]=u;
}
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
54
Design and Analysis of Algorithms -21CS42- Laboratory Component
}
for(i=1;i<=n;i++)
if(d[i]==999)
else
for(i=1;i<=n;i++)
System.out.print(i);
j=p[i];
while(p[j]!=0)
j=p[j];
System.out.println("<----"+ v +"\n");
}
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
55
Design and Analysis of Algorithms -21CS42- Laboratory Component
}
int i,j,n,v;
n=in.nextInt();
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
w[i][j]=in.nextInt();
v=in.nextInt();
d1.dijkstra(v,w,s,d,n);
Output:
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
56
Design and Analysis of Algorithms -21CS42- Laboratory Component
enter the number of vertices
3
enter the cost of vertices
999 2 3
2 999 4
3 4 999
enter the source vertex
1
shortest path costs
path cost from1to1is:0
path cost from1to2is:2
path cost from1to3is:3
shortest group of paths are
2<----1
3<----1
3. Write & Execute C++/Java Program to find Minimum Cost Spanning Tree of a given
connected undirected graph using Kruskal's algorithm. Use Union-Find algorithms in
your program.
A disjoint-set data structure is a data structure that keeps track of a set of elements partitioned
into a number of disjoint (non-overlapping) subsets. A union-find algorithm is an algorithm that
performs two useful operations on such a data structure:
Find: Determine which subset a particular element is in. This can be used for determining if two
elements are in the same subset.
Union: Join two subsets into a single subset.
In this post, we will discuss an application of Disjoint Set Data Structure. The application is to
check whether a given graph contains a cycle or not.
Union-Find Algorithm can be used to check whether an undirected graph contains cycle or not.
This method is based on Union-Find. This method assumes that graph doesn’t contain any self-
loops.
Pseudocode: Kruskal(G)
//Kruskal’s algorithm for constructing a minimum spanning tree
// Input: A weighted connected graph G=V, E
// Output: ET , the set of edges composing a minimum spanning tree of G
Sort E in non-decreasing order of the edge weights w(ei1)<=…<=w(ei|E|)
ET ; ecounter 0 //initialise the set of tree edges and its size
k0 //initialise the number of processed edges
while ecounter < |V| - 1
kk+1
if ET {eik}is acyclic
ETET {eik}; ecounter ecounter+1
Return ET
Program 3
import java.util.Scanner;
while(s[v]!=v)
v=s[v];
return v;
s[i]=j;
int count,i,min,j,u=0,v=0,k,sum;
for(i=0;i<n;i++)
s[i]=i;
count=0;
k=0;
while(count<n-1)
min=999;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
min=c[i][j];
u=i;
v=j;
if(min==999) break;
i=find(u,s);
j=find(v,s);
if(i!=j)
t[k][0]=u;
t[k][1]=v;
k++;
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
60
Design and Analysis of Algorithms -21CS42- Laboratory Component
count++;
sum+=min;
union1(i,j,s);
c[u][v]=c[v][u]=999;
if(count==n-1)
for(k=0;k<n-1;k++)
System.out.println("\n"+t[k][0]+","+t[k][1]);
int n,i,j;
System.out.println("Enter no of nodes\n");
n=in.nextInt();
for(j=0;j<n;j++)
c[i][j]=in.nextInt();
kruskal(n,c);
Output:
Enter no of nodes
6
Enter the cost adjacency matrix
999 3 999 999 6 5
3 999 1 999 999 4
999 1 999 6 999 4
999 999 6 999 8 5
6 999 999 8 999 2
5 4 4 5 2 999
cost of spanning tree=15
spanning tree is
1,2
4,5
0,1
1,5
3,5
4. Write & Execute C++/Java Program to find Minimum Cost Spanning Tree of a given
connected undirected graph using Prim's algorithm.
Pseudocode:Prim(G)
//Prim’s algorithm for constructing a minimum spanning tree
//Input: A weighted connected graph G = {V, E}
//Output: Et, the set of edges composing a minimum spanning tree of G
Vt←{v0} //the set of tree vertices can be initialized with any vertex
Et←∅
for i ←1 to |V| − 1 do
find a minimum-weight edge e∗ = (v∗, u∗) among all the edges (v, u)
such that v is in Vtand u is in V − Vt
Vt←Vt ∪ {u∗}
Et←Et ∪ {e∗}
return Et
Program 4
import java.util.Scanner;
int ne=1;
int min_cost=0;
n=in.nextInt();
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cost[i][j]=in.nextInt();
for(i=1;i<=n;i++)
visited[i]=0;
source=in.nextInt();
visited[source]=1;
while(ne<n)
min=999; for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
64
Design and Analysis of Algorithms -21CS42- Laboratory Component
if(cost[i][j]<min) if(visited[i]==0)
continue;
else
min=cost[i][j];
a=u=i;
b=v=j;
if(visited[u]==0||visited[v]==0)
ne++;
min_cost=min_cost+min;
visited[b]=1;
cost[a][b]=cost[b][a]=999;
System.out.println("\nMinimum cost="+min_cost+"\n");
Output:
1) Write C++/ Java programs to solve All-Pairs Shortest Paths problem using Floyd's
algorithm.
.
Floyd’s Algorithm for All-Pairs Shortest-Paths Problem using Dynamic Programming
Given a weighted connected graph (undirected or directed), the all-pairs shortest paths problem
asks to find the distances—i.e., the lengths of the shortest paths—from each vertex to all other
vertices. This is one of several variations of the problem involving shortest paths in graphs.
Because of its important applications to communications, transportation networks, and
operations research, it has been thoroughly studied over the years. Among recent applications of
the all-pairs shortest-path problem is precomputing distances for motion planning in computer
games.
It is convenient to record the lengths of shortest paths in an n × n matrix D called the distance
matrix: the element dij in the ith row and the jth column of this matrix indicates the length of the
shortest path from the ith vertex to the jth vertex. We can generate the distance matrix with an
algorithm that is very similar toWarshall’s algorithm. It is called Floyd’s algorithm after its co-
inventor Robert W. Floyd. It is applicable to both undirected and directed weighted graphs
provided that they do not contain a cycle of a negative length. (The distance between any two
vertices in such a cycle can be made arbitrarily small by repeating the cycle enough times.) The
algorithm can be enhanced to find not only the lengths of the shortest paths for all vertex pairs
but also the shortest paths themselves.
Floyd’s algorithm computes the distance matrix of a weighted graph with n vertices through a
series of n × n matrices:
D(0), . . . , D(k−1), D(k), . . . , D(n).
Pseudocode:Floyd(W[1..n, 1..n])
//Implements Floyd’s algorithm for the all-pairs shortest-paths problem
//Input: The weight matrix W of a graph with no negative-length cycle
//Output: The distance matrix of the shortest paths’ lengths
D ←W //is not necessary if W can be overwritten
for k←1 to n do
for i ←1 to n do
for j ←1 to n do
D[i, j ]←min{D[i, j ], D[i, k]+ D[k, j]}
return D
Program 1
import java.util.Scanner;
int i,j,k;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
d[i][j]=a[i][j];
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
}
public static int min (int a,int b)
{
if(a<b)
return a;
else
return b;
}
public static void main(String args[])
int n,i,j;
n=sc.nextInt();
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]= sc.nextInt();
floyd(a,n);
}
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
69
Design and Analysis of Algorithms -21CS42- Laboratory Component
Output:
For example, consider the graph shown in figure on right side. A TSP tour in the graph is 1-2-4-
3-1. The cost of the tour is 10+25+30+15 which is 80.The problem is a famous NP hard problem.
There is no polynomial time know solution for this problem.
Following are different solutions for the travelling salesman problem.
Naive Solution:
1) Consider city 1 as the starting and ending point.
2) Generate all (n-1)! Permutations of cities.
3) Calculate cost of every permutation and keep track of minimum cost permutation.
4) Return the permutation with minimum cost.
Time Complexity: (n!)
Dynamic Programming:
Denote the cities by 1,...,n, the starting city being 1, and let D = (dij) be the matrix of intercity
distances. The goal is to design a tour that starts and ends at 1, includes all other cities exactly
once, and has minimum total length. Figure shows an example involving five cities.
Let's dive right into the DP. So what is the appropriate sub-problem for the TSP? In this case the
most obvious partial solution is the initial portion of a tour. Suppose we have started at city 1 as
required, have visited a few cities, and are now in city j. What information do we need in order to
extend this partial tour? We certainly need to know j, since this will determine which cities are
most convenient to visit next. And we also need to know all the cities visited so far, so that we
don’t repeat any of them. Here, then, is an appropriate sub-problem.
For a subset of cities S ⊆ {1,2,...,n} that includes 1, and j ∈ S, let C(S,j) be the length of the
shortest path visiting each node in S exactly once, starting at 1 and ending at j.
When |S| > 1, we define C(S, 1) = ∞ since the path cannot both start and end at 1.
Now, let’s express C(S,j) in terms of smaller sub-problems. We need to start at 1 and end at j;
what should we pick as the second-to-last city? It has to be some i ∈ S, so the overall path length
is the distance from 1 to i, namely, C(S − {j}, i), plus the length of the final edge, dij.
We must pick the best such i:
C(S,j)=mini∈S:i≠jC(S−{j},i)+dij
Program 2
import java.util.Scanner;
int i,j,k;
int mincost,ccost;
if(start==n-2)
return(c[tour[n-2]][tour[n-1]]+c[tour[n-1]][0]);
mincost=INFINITY;
for(i=start+1;i<n;i++)
for(j=0;j<n;j++)
temp[j]=tour[j];
temp[start+1]=tour[i];
temp[i]=tour[start+1];
if(c[tour[start]][tour[i]]+(ccost=tsp_dp(c,temp,start+1,n))<mincost)
mincost=ccost+c[tour[start]][tour[i]];
for(k=0;k<n;k++)
mintour[k]=temp[k];
}
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
73
Design and Analysis of Algorithms -21CS42- Laboratory Component
for(i=0;i<n;i++)
tour[i]=mintour[i];
tour[i]=start;
return mincost;
int n,i,j,cost;
n=sc.nextInt();
for(i=0;i<n;i++)
for(j=0;j<n;j++)
c[i][j]=sc.nextInt();
for(i=0;i<n;i++)
tour[i]=i;
cost=tsp_dp(c,tour,0,n);
System.out.println("\nmincost by dp:"+cost);
System.out.println("\ntour: ");
for(i=0;i<n;i++)
System.out.print(tour[i]+1 +"\t");
}
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
74
Design and Analysis of Algorithms -21CS42- Laboratory Component
}
Output:
Given weights and values of n items, put these items in a knapsack of capacity W to get the
maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and
wt[0..n-1] which represent values and weights associated with n items respectively. Also given
an integer W which represents knapsack capacity, find out the maximum value subset of val[]
such that sum of the weights of this subset is smaller than or equal to W. You cannot break an
item, either pick the complete item, or don’t pick it (0-1 property).
A simple solution is to consider all subsets of items and calculate the total weight and value of all
subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets,
pick the maximum value subset.
Optimal Substructure:
To consider all subsets of items, there can be two cases for every item:
(1) the item is included in the optimal subset, (2) not included in the optimal set.
Therefore, the maximum value that can be obtained from n items is max of following two values.
1) Maximum value obtained by n-1 items and W weight (excluding nth item).
2) Value of nth item plus maximum value obtained by n-1 items and W minus weight of the nth
item (including nth item).
If weight of nth item is greater than W, then the nth item cannot be included and case 1 is the
only possibility.
max(a,b)
{
return(a>b)?a:b;
}
knap(i, j)
{
if(i=0 or j=0) then
v[i][j]=0
elseif(j<w[i]) then
v[i][j]=knap(i-1,j)
else
v[i][j]=max(knap(i-1,j), value[i]+knap(i-1,j-w[i]))
returnv[i][j]
}
optimal( i,j)
{
if(i>=1 or j>=1) then
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
76
Design and Analysis of Algorithms -21CS42- Laboratory Component
if(v[i][j]!=v[i-1][j]) then
{
Print Item i
b[i]=1
j=j-w[i]
optimal(i-1,j)
}
else
optimal(i-1,j);
}
Program 3
import java.util.Scanner;
public class Knapsack1
{
private static int w[]=new int[10];
private static int b[]=new int[10];
private static int v[][]=new int[10][10];
private static int value[]=new int[10];
static int max(int a, int b)
{
return(a>b)?a:b;
}
static int knap(int i,int j)
{
if(i==0 || j==0)
v[i][j]=0;
else if(j<w[i])
v[i][j]=knap(i-1,j);
else
v[i][j]=max(knap(i-1,j), value[i]+knap(i-1,j-w[i]));
return v[i][j];
}
static void optimal(int i,int j)
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
77
Design and Analysis of Algorithms -21CS42- Laboratory Component
{
if(i>=1 || j>=1)
if(v[i][j]!=v[i-1][j])
{
System.out.println("Item:"+i);
b[i]=1;
j=j-w[i];
optimal(i-1,j);
}
else
optimal(i-1,j);
}
public static void main(String[] args)
{
int profit, w1,n,i,j;
Scanner sc=new Scanner(System.in);
System.out.println("enter the number of items:");
n=sc.nextInt();
System.out.println("enter the capacity of the knapsack:");
w1=sc.nextInt();
System.out.println("enter the values:");
for(i=1;i<=n;i++)
value[i]=sc.nextInt();
System.out.println("enter the weights:");
for(i=1;i<=n;i++)
w[i]=sc.nextInt();
profit=knap(n,w1);
System.out.println("profit: "+profit);
System.out.println("\n optimal subset is:\n");
optimal(n,w1);
System.out.println("the solution vector is:");
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
78
Design and Analysis of Algorithms -21CS42- Laboratory Component
for(i=1;i<=n;i++)
System.out.println(b[i]);
}
}
Output:
enter the number of items:
4
enter the capacity of the knapsack:
2
enter the values:
3
45
4
3
enter the weights:
1
1
1
1
profit: 49
Item:3
Item:2
the solution vector is:
0
1
1
0
1. Design and implement C++/Java Program to find a subset of a given set S = {Sl, S2,…,
Sn} of n positive integers whose SUM is equal to a given positive integer d. For example, if
S = {1, 2, 5, 6, 8} and d= 9, there are two solutions {1, 2, 6} and {1, 8}. Display a suitable
message, if the given problem instance doesn't have a solution.
Pseudocode:
sumofsub(0,1,sum)
{
x[k]=1
if(s +w[k] <- u)
{
print solution v++
for i<- 1 to n do
if x[i]=1
print w[i]
}
else if (s+ w[k] +w[k+] < = m) do
call sumofsub(s + w[k],k+1 , r-w[k])
if( s +r-w[k]>=m and s+w[k+] <=m) do
{
x[k]<-0
call sumofsub(s,k+1,r-w[k])
}
}
Program 1
import java.util.Scanner;
public class Subset
{
private static int d;
private static int count=0;
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
80
Design and Analysis of Algorithms -21CS42- Laboratory Component
private static int x[]=new int[20];
private static int w[]=new int[20];
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int i,n,sum=0;
System.out.println("Enter the no. of elements: ");
n=sc.nextInt();
System.out.println("\nEnter the elements in ascending order:\n");
for(i=0;i<n;i++)
w[i]=sc.nextInt();
System.out.println("\nEnter the sum: ");
d=sc.nextInt();
for(i=0;i<n;i++)
sum=sum+w[i];
if(sum<d)
{
System.out.println("No solution\n");
return;
}
subset(0,0,sum);
if(count==0)
{
System.out.println("No solution\n");
return;
}
}
static void subset(int cs,int k,int r)
{
int i;
x[k]=1;
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
81
Design and Analysis of Algorithms -21CS42- Laboratory Component
if(cs+w[k]==d)
{
System.out.println("\n\nSubset" +(++count));
for(i=0;i<=k;i++)
if(x[i]==1)
System.out.println(w[i]+" ");
}
else if(cs+w[k]+w[k+1]<=d)
{
subset((cs+w[k]),k+1,r-w[k]);
}
if(cs+r-w[k]>=d && cs+w[k]<=d)
{
x[k]=0;
subset(cs,k+1,r-w[k]);
}
}
}
Output:
Enter the no. of elements:
5
Enter the elements in ascending order:
12568
Enter the sum:
9
Subset1
1
2
6
Subset2
1
8
Graph shown in Fig.1 does not contain any Hamiltonian Path. Graph shown in Fig. 2 contains
two Hamiltonian Paths which are highlighted in Fig. 3 and Fig. 4
Following are some ways of checking whether a graph contains a Hamiltonian Path or not.
1. A Hamiltonian Path in a graph having N vertices is nothing but a permutation of the
vertices of the graph [v1, v2, v3, ......vN-1, vN] , such that there is an edge between vi and
vi+1 where 1 ≤ i ≤ N-1. So it can be checked for all permutations of the vertices whether
any of them represents a Hamiltonian Path or not. For example, for the graph given in
Fig. 2 there are 4 vertices, which means total 24 possible permutations, out of which only
following represents a Hamiltonian Path.
0-1-2-3
3-2-1-0
0-1-3-2
2-3-1-0
2. Pseudocode:
function check_all_permutations(adj[][], n)
{
for i = 0 to n
p[i]=i
while next permutation is possible
valid = true
for i = 0 to n-1
if adj[p[i]][p[i+1]] == false
valid = false
break
if valid == true
return true
p = get_next_permutation(p)
return false
Program 2
public class Hamiltonian
{
final int V = 5;
int path[];
/* A utility function to check if the vertex v can be added at index 'pos'in the Hamiltonian
Cycle constructed so far (stored in 'path[]') */
/* Check if the vertex has already been included.This step can be optimized by creating
an arrayof size V */
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
return true;
}
/* A recursive utility function to solve hamiltonian cycle problem */
boolean hamCycleUtil(int graph[][], int path[], int pos)
{
/* base case: If all vertices are included in Hamiltonian Cycle */
if (pos == V)
{
// And if there is an edge from the last included
// vertex to the first vertex
if (graph[path[pos - 1]][path[0]] == 1)
return true;
else
return false;
}
/* Try different vertices as a next candidate in Hamiltonian Cycle. We don't try for 0 as
We included 0 as starting point in hamCycle() */
for (int v = 1; v < V; v++)
{
/* Check if this vertex can be added to Hamiltonian Cycle */
if (isSafe(v, graph, path, pos))
{
path[pos] = v;
/* recur to construct rest of the path */
if (hamCycleUtil(graph, path, pos + 1) == true)
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
85
Design and Analysis of Algorithms -21CS42- Laboratory Component
return true;
/* If adding vertex v doesn't lead to a solution,then remove it */
path[pos] = -1;
}
}
/* If no vertex can be added to Hamiltonian Cycle constructed so far, then return false */
return false;
}
/* This function solves the Hamiltonian Cycle problem using Backtracking. It mainly uses
hamCycleUtil() to solve the problem. It returns false if there is no Hamiltonian Cycle
possible, otherwise return true and prints the path.Please note that there may be more
than one solutions this function prints one of the feasible solutions. */
/* Let us put vertex 0 as the first vertex in the path.If there is a Hamiltonian Cycle,
then the path can be started from any point of the cycle as the graph is undirected */
path[0] = 0;
if (hamCycleUtil(graph, path, 1) == false)
{
//System.out.println("\nSolution does not exist");
return 0;
}
printSolution(path);
return 1;
}
Dept. of CSE, SIR MVIT, Bengaluru AY2022-2023
86
Design and Analysis of Algorithms -21CS42- Laboratory Component