SJBIT (Design and Analysis of Algorithm Lab Manual)
SJBIT (Design and Analysis of Algorithm Lab Manual)
INTRODUCTION
An algorithm is a description of a procedure which terminates with a result. It is a step
by step procedure designed to perform an operation, and which will lead to the sought result
if followed correctly. Algorithms have a definite beginning and a definite end, and a finite
number of steps. An algorithm produces the same output information given the same input
information, and several short algorithms can be combined to perform complex tasks.
PROPERTIES OF ALGORITHMS
1. Finiteness – an algorithm must terminate after a finite number of steps.
2. Definiteness – each step must be precisely defined.
3. Effective – all operations can be carried out exactly in finite time.
4. Input – an algorithm has one or more outputs.
MODELS OF COMPUTATION
There are many ways to compute the algorithm’s complexity; they are all equivalent in
some sense.
1. Turing machines.
2. Random access machines (RAM).
3. λ Calculus.
4. Recursive functions.
5. Parallel RAM (PRAM).
For the analysis of algorithms, the RAM model is most often employed. Note time does
not appear to be reusable, but space often is.
MEASURING AN ALGORITHM’S COMLEXITY
General consideration of time and space is:
One time unit per operation.
One space unit per value (all values fit in fixed size register).
There are other considerations:
On real machines, different operations typically take different times to execute.
This will generally be ignored, but sometimes we may wish to count different
types of operations, e.g., Swaps and compares, or additions and multiplications.
Some operations may be “noise” not truly affecting the running time; we typically
only count “major” operations example, for loop index arithmetic and boundary
checking is “noise.” operations inside for loops are usually “major.”
Logarithmic cost model: it takes ⌊lg n ⌋ +1 bits to represent natural number n
in binary notation. Thus the uniform model of time and space may not bias results
for large integers (data).
An algorithm solves an instance of a problem. There is, in general, one parameter, the
input size, denoted by n, which is used to characterize the problem instance. The input size n
is the number of registers needed to hold input (data segment size).
Given n, we’d like to find:
1. The time complexity, denoted by T(n), which is the count of operations the algorithm
performs on the given input.
1
Design & Analysis of Algorithms Laboratory Manual
2. The space complexity, denoted by S(n), which is the number of memory registers
used by the algorithm (stack/heap size, registers).
Note that T(n) and S(n) are relations rather than functions. That is, for different input of the
same size n, T(n) and S(n) may provide different answers.
WORST, AVERAGE, BEST, AND MORTIZED COMPLEXITY
Complexities usually not measured exactly: big- O, Ω, and Θ notation is used.
WORST CASE:
This is the longest time (or most space) that the algorithm will use over all instances
of size n. Often this can be represented by a function f(n) such as f(n)=n2 or f(n)=n lg n. We
write T(n)= O(f(n)) for the worst case time complexity. Roughly, this means the algorithm
will take mo more than f(n) operations.
BEST CASE:
This is the shortest time that the algorithm will use over all instances of size n. often
this can be represented by a function f(n) such as f(n)=n2 or f(n)=n lg n. We write T(n)= Ω
(f(n)) for the best case. Roughly, this means the algorithm will take no less than f(n)
operations. The best case is seldom interesting.
When the worst and best case performance of an algorithm are the same we can write
T(n)= Θ (f(n)). Roughly, this says the algorithm always uses f(n) operations on all
instances of size n.
AVERAGE CASE:
This is the average time that the algorithm will use over all instances if size n. it
depends on the probability distribution of instances of the problem.
AMORTIZED COST:
This is used when a sequence of operations occur, e.g., inserts and deletes in a tress,
where the costs vary depending on the operations and their order. For example, some may
take a few steps, some many.
TYPES OF ALGORITHMS
1. Off-line algorithms: all input in memory before time starts, want final result.
2. On-line: input arrives at discrete time steps, intermediate result furnished before next
input.
3. Real-time: elapsed time between two inputs (outputs) is a constant O(1).
COMPLEXITY CLASSES
Collection of problems that required roughly the same amount of resources from complexity
classes. Here is a list of the most important:
1. The class P of problems that can be solved in a polynomial number of operations of
the input size on a deterministic Turing machine.
2. The class NP of problems that can be solved in a polynomial number of operations of
the input size on a non-deterministic Turing machine.
3. The class of problems that can be solved in a constant amount of space.
4. The class L that can be solved in a logarithmic amount of space based on the input
size.
2
Design & Analysis of Algorithms Laboratory Manual
5. The class PSPACE of problems that can be solved in a polynomial amount of space
based on the input size.
6. The class NC of problems that can be solved in poly-logarithmic time on a
polynomial number of processors.
ALGORITHM PARADIGMS
Often there are large collections of problems that can be solved using the same general
techniques or paradigms. A few of the most common are described below:
Brute Force:
A straightforward approach to solving a problem based on the problem statement and
concepts involved. Brute force algorithms are rarely efficient. Example algorithms
include:
Bubble sort.
Computing the sum of n numbers by direct addition.
Standard matrix multiplication.
Linear search.
Divide and Conquer:
Perhaps the most famous algorithm paradigm, divide and conquer is based on partitioning the
problem into two or more smaller sub-problems, solving them and combining the sub-
problem solutions into a solution for the original problem. Example algorithms include:
Merge sort and quick sort.
The Fast Fourier Transform (FFT).
Stassen’s matrix multiplication.
Greedy Algorithms:
Greedy algorithms always make the choice that seems best at the moment. This is locally
optimal choice is made with the hope that it leads to a globally optimal solution. Some greedy
algorithms may not be guaranteed to always produce an optimal solution.
Greedy algorithms are often applied to combinatorial optimization problems.
Given an instance 1 of the problem.
There is a set of candidates or feasible solutions that satisfy the constraints of the
problem.
For each feasible solution there is a value determined by an objective function.
An optimal solution minimizes (or maximizes) the value of objective function.
Example algorithms include:
Kruskal’s and Prim’s minimal spanning tree algorithms.
Dijkstra’s single source shortest path algorithm.
Huffman coding.
Dynamic Programming:
A nutshell definition of dynamic programming is difficult, but to summarize, problems which
lend themselves to a dynamic programming attack have the following characteristics:
3
Design & Analysis of Algorithms Laboratory Manual
4
Design & Analysis of Algorithms Laboratory Manual
1. A. Create a Java class called Student with the following details as variables
within it. (i)USN (ii)Name (iii)Branch (iv)Phone. Write a Java program to create
‘n’ Student objects and print the USN, Name, Branch, and Phone of these objects
with suitable headings.
import java.util.Scanner;
class Student {
void read() {
System.out.println("Enter Student Details");
System.out.println("Enter USN");
USN = input.nextLine();
System.out.println("Enter Name");
Name = input.nextLine();
System.out.println("Enter Branch");
Branch = input.nextLine();
System.out.println("Enter Phone");
Phone = input.nextLine();
}
void display() {
System.out.printf("%-20s %-20s %-20s %-20s", USN, Name, Branch,
Phone);
}
}
class studentdetails {
public static void main(String[] args) {
5
Design & Analysis of Algorithms Laboratory Manual
Output:
Enter Number of Students: 3
Enter Student Details
Enter Student USN: 1DT14cs001
Enter Student NAME: AAA
Enter Student BRANCH: CSE
Enter Student PHONENUMBER: 9999900000
Enter Student Details
Enter Student USN:1DT14cs002
Enter Student NAME: BBB
Enter Student BRANCH: CSE
Enter Student PHONENUMBER: 9999911111
Enter Student Details
Enter Student USN: 1DT14CS003
Enter Student NAME: CCC
Enter Student BRANCH: CSE
Enter Student PHONENUMBER: 9999922222
USN NAME BRANCH PHONENUMBER
1DT14cs001 AAA CSE 9999900000
1DT14cs002 BBB CSE 9999911111
1DT14CS003 CCC CSE 9999922222
6
Design & Analysis of Algorithms Laboratory Manual
B. Write a Java program to implement the Stack using arrays. Write Push(),
Pop(), and Display() methods to demonstrate its working.
import java.util.*;
class arrayStack {
int arr[];
int top, max;
arrayStack(int n) {
max = n;
arr = new int[max];
top = -1;
}
void push(int i) {
if (top == max - 1)
System.out.println("Stack Overflow");
else
arr[++top] = i;
}
void pop() {
if (top == -1) {
System.out.println("Stack Underflow");
} else {
int element = arr[top--];
System.out.println("Popped Element: " + element);
}
}
void display() {
System.out.print("\nStack = ");
if (top == -1) {
System.out.print("Empty\n");
return;
}
for (int i = top; i >= 0; i--)
System.out.print(arr[i] + " ");
System.out.println();
}
}
class Stack {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter Size of Integer Stack ");
int n = scan.nextInt();
boolean done = false;
7
Design & Analysis of Algorithms Laboratory Manual
char ch;
do {
System.out.println("\nStack Operations");
System.out.println("1. push");
System.out.println("2. pop");
System.out.println("3. display");
System.out.println("4. Exit");
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
case 4:
done = true;
break;
default:
System.out.println("Wrong Entry \n ");
break;
} while (!done);
}
}
Output:
8
Design & Analysis of Algorithms Laboratory Manual
1
Enter the element to be pushed: 10
Enter the stack operation: 1
Enter the element to be pushed: 20
Enter the stack operation: 1
Enter the element to be pushed: 30
Enter the stack operation: 1
Enter the element to be pushed: 40
Enter the stack operation: 1
Enter the element to be pushed: 50
stack is full
Enter the stack operation: 3
Elements in stack :
10
20
30
40
Enter the stack operation: 2
Deleted element is: 40
Enter the stack operation: 2
Deleted element is: 30
Enter the stack operation: 2
Deleted element is: 20
Enter the stack operation: 2
Deleted element is:10
Enter the stack operation: 2
stack is empty
Enter the stack operation: 3
stack is empty
Enter the stack operation : 4
9
Design & Analysis of Algorithms Laboratory Manual
2. Design a super class called Staff with details as StaffId, Name, Phone, Salary.
Extend this class by writing three subclasses namely Teaching (domain,
publications), Technical (skills), and Contract (period). Write a Java program to
read and display at least 3 staff objects of all three categories.
import java.util.Scanner;
class Staff {
String StaffID, Name, Phone, Salary;
void read() {
System.out.println("Enter StaffID");
StaffID = input.nextLine();
System.out.println("Enter Name");
Name = input.nextLine();
System.out.println("Enter Phone");
Phone = input.nextLine();
System.out.println("Enter Salary");
Salary = input.nextLine();
}
void display() {
System.out.printf("\n%-15s", "STAFFID: ");
System.out.printf("%-15s \n", StaffID);
System.out.printf("%-15s", "NAME: ");
System.out.printf("%-15s \n", Name);
System.out.printf("%-15s", "PHONE:");
System.out.printf("%-15s \n", Phone);
System.out.printf("%-15s", "SALARY:");
System.out.printf("%-15s \n", Salary);
}
}
void read_Teaching() {
super.read(); // call super class read method
System.out.println("Enter Domain");
Domain = input.nextLine();
System.out.println("Enter Publication");
Publication = input.nextLine();
}
10
Design & Analysis of Algorithms Laboratory Manual
void display() {
super.display(); // call super class display() method
System.out.printf("%-15s", "DOMAIN:");
System.out.printf("%-15s \n", Domain);
System.out.printf("%-15s", "PUBLICATION:");
System.out.printf("%-15s \n", Publication);
}
}
void read_Technical() {
super.read(); // call super class read method
System.out.println("Enter Skills");
Skills = input.nextLine();
}
void display() {
super.display(); // call super class display() method
System.out.printf("%-15s", "SKILLS:");
System.out.printf("%-15s \n", Skills);
}
}
void read_Contract() {
super.read(); // call super class read method
System.out.println("Enter Period");
Period = input.nextLine();
}
void display() {
super.display(); // call super class display() method
System.out.printf("%-15s", "PERIOD:");
System.out.printf("%-15s \n", Period);
}
}
class Staffdetails {
public static void main(String[] args) {
11
Design & Analysis of Algorithms Laboratory Manual
int n = input.nextInt();
System.out.println();
System.out.println("-----TECHNICAL STAFF DETAILS-----");
for (int i = 0; i < n; i++) {
stech[i].display();
}
System.out.println();
System.out.println("-----CONTRACT STAFF DETAILS-----");
for (int i = 0; i < n; i++) {
scon[i].display();
}
input.close();
}
}
12
Design & Analysis of Algorithms Laboratory Manual
Output:
run:
Enter number of staff details to be created
3
Enter Teaching staff information
Enter StaffID
11
Enter Name
aaa
Enter Phone
9999900000
Enter Salary
100000
Enter Domain
Network
Enter Publication
4
Enter Teaching staff information
Enter StaffID
22
Enter Name
BBB
Enter Phone
9999911111
Enter Salary
100000
Enter Domain
Java
Enter Publication
3
Enter Teaching staff information
Enter StaffID
33
Enter Name
CCC
Enter Phone
9999922222
Enter Salary
100000
Enter Domain
C++
Enter Publication
5
Enter Technical staff information
Enter StaffID
44
Enter Name
DDD
Enter Phone
13
Design & Analysis of Algorithms Laboratory Manual
9999933333
Enter Salary
10000
Enter Skills
Programing
Enter Technical staff information
Enter StaffID
55
Enter Name
EE
Enter Phone
9999944444
Enter Salary
20000
Enter Skills
C++ Prog
Enter Technical staff information
Enter StaffID
66
Enter Name
FF
Enter Phone
9999966666
Enter Salary
30000
Enter Skills
Java Prog
Enter Contract staff information
Enter StaffID
77
Enter Name
XYZ
Enter Phone
9999977777
Enter Salary
10000
Enter Period
4
Enter Contract staff information
Enter StaffID
88
Enter Name
GGG
Enter Phone
9999988888
Enter Salary
10000
Enter Period
3
Enter Contract staff information
14
Design & Analysis of Algorithms Laboratory Manual
Enter StaffID
99
Enter Name
HHH
Enter Phone
99999010101
Enter Salary
20000
Enter Period
5
STAFF DETAILS:
STAFFID: 11
NAME: aaa
PHONE: 9999900000
SALARY: 100000
DOMAIN: Network
PUBLICATION: 4
STAFFID: 22
NAME: BBB
PHONE: 9999911111
SALARY: 100000
DOMAIN: Java
PUBLICATION: 3
STAFFID: 33
NAME: CCC
PHONE: 9999922222
SALARY: 100000
DOMAIN: C++
PUBLICATION: 5
STAFFID: 44
NAME: DDD
PHONE: 9999933333
SALARY: 10000
SKILLS: Programing
STAFFID: 55
NAME: EE
PHONE: 9999944444
SALARY: 20000
SKILLS: C++ Prog
15
Design & Analysis of Algorithms Laboratory Manual
STAFFID: 66
NAME: FF
PHONE: 9999966666
SALARY: 30000
SKILLS: Java Prog
STAFFID: 77
NAME: XYZ
PHONE: 9999977777
SALARY: 10000
PERIOD: 4
STAFFID: 88
NAME: GGG
PHONE: 9999988888
SALARY: 10000
PERIOD: 3
STAFFID: 99
NAME: HHH
PHONE: 99999010101
SALARY: 20000
PERIOD: 5
BUILD SUCCESSFUL (total time: 4 minutes 32 seconds)
16
Design & Analysis of Algorithms Laboratory Manual
B. Write a Java class called Customer to store their name and date_of_birth. The
date_of_birth format should be dd/mm/yyyy. Write methods to read customer
data as <name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using
StringTokenizer class considering the delimiter character as “/”.
import java.util.Scanner;
import java.util.StringTokenizer;
Output:
Enter Name and Date_of_Birth in the format <Name,DD/MM/YYYY>
AAA,30/06/1989
AAA,30,06,1989
17
Design & Analysis of Algorithms Laboratory Manual
3. A. Write a Java program to read two integers a and b. Compute a/b and print,
when b is not zero. Raise an exception when b is equal to zero.
import java.util.Scanner;
class exception {
a = input.nextInt();
b = input.nextInt();
try {
result = a / b;
System.out.println("Result = " + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
}
}
}
Output:
Input two integers
10
2
Result = 5
18
Design & Analysis of Algorithms Laboratory Manual
import java.util.Random;
SquareThread(int x) {
this.x = x;
}
CubeThread(int x) {
this.x = x;
}
19
Design & Analysis of Algorithms Laboratory Manual
while (true) {
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
t2 = new Thread(new SquareThread(num));
t2.start();
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
} catch (Exception ex) {
System.out.println("Interrupted Exception");
}
}
}
Output:
Main Thread and Generated Number is 73
Thread Name:Square Thread and Square of 73 is: 5329
Thread Name:Cube Thread and Cube of 73 is: 389017
20
Design & Analysis of Algorithms Laboratory Manual
--------------------------------------
Main Thread and Generated Number is 96
Thread Name:Square Thread and Square of 96 is: 9216
Thread Name:Cube Thread and Cube of 96 is: 884736
--------------------------------------
Main Thread and Generated Number is 30
Thread Name:Square Thread and Square of 30 is: 900
Thread Name:Cube Thread and Cube of 30 is: 27000
--------------------------------------
Main Thread and Generated Number is 77
Thread Name:Square Thread and Square of 77 is: 5929
Thread Name:Cube Thread and Cube of 77 is: 456533
--------------------------------------
Main Thread and Generated Number is 63
Thread Name:Square Thread and Square of 63 is: 3969
Thread Name:Cube Thread and Cube of 63 is: 250047
--------------------------------------
Main Thread and Generated Number is 97
Thread Name:Square Thread and Square of 97 is: 9409
Thread Name:Cube Thread and Cube of 97 is: 912673
--------------------------------------
Main Thread and Generated Number is 75
Thread Name:Square Thread and Square of 75 is: 5625
Thread Name:Cube Thread and Cube of 75 is: 421875
--------------------------------------
Main Thread and Generated Number is 79
Thread Name:Square Thread and Square of 79 is: 6241
Thread Name:Cube Thread and Cube of 79 is: 493039
--------------------------------------
Main Thread and Generated Number is 22
Thread Name:Square Thread and Square of 22 is: 484
Thread Name:Cube Thread and Cube of 22 is: 10648
--------------------------------------
Main Thread and Generated Number is 31
Thread Name:Square Thread and Square of 31 is: 961
Thread Name:Cube Thread and Cube of 31 is: 29791
--------------------------------------
Main Thread and Generated Number is 37
Thread Name:Square Thread and Square of 37 is: 1369
Thread Name:Cube Thread and Cube of 37 is: 50653
--------------------------------------
Main Thread and Generated Number is 98
Thread Name:Square Thread and Square of 98 is: 9604
Thread Name:Cube Thread and Cube of 98 is: 941192
--------------------------------------
Main Thread and Generated Number is 9
Thread Name:Square Thread and Square of 9 is: 81
Thread Name:Cube Thread and Cube of 9 is: 729
--------------------------------------
21
Design & Analysis of Algorithms Laboratory Manual
4. 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 on graph sheet. The
elements can be read from a file or can be generated using the random number
generator. Demonstrate using Java how the divide-and-conquer method works
along with its time complexity analysis: worst case, average case and best case.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
System.out.println("Input Array:");
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
// set start time
long startTime = System.nanoTime();
QuickSortAlgorithm(0, n - 1);
long stopTime = System.nanoTime();
long elapsedTime = stopTime - startTime;
System.out.println("\nSorted Array:");
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
System.out.println();
System.out.println("Time Complexity in ms for
n=" + n + " is: " + (double) elapsedTime / 1000000);
}
22
Design & Analysis of Algorithms Laboratory Manual
Output
Enter Max array size: 20
Enter the array elements:
Input Array:
326 719 983 701 490 230 595 474 341 75 916 173 324 852 728 434 758 445 303 566
Sorted Array:
75 173 230 303 324 326 341 434 445 474 490 566 595 701 719 728 758 852 916 983
Time Complexity in ms for n=20 is: 0.023225
23
Design & Analysis of Algorithms Laboratory Manual
24
Design & Analysis of Algorithms Laboratory Manual
5. 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 on graph sheet. The
elements can be read from a file or can be generated using the random number
generator. Demonstrate using Java how the divide-and-conquer method works
along with its time complexity analysis: worst case, average case and best case.
import java.util.Random;
import java.util.Scanner;
25
Design & Analysis of Algorithms Laboratory Manual
if (h > mid)
for (k = j; k <= high; k++)
b[i++] = a[k];
else
for (k = h; k <= mid; k++)
b[i++] = a[k];
Output
Enter Max array size: 5
Enter the array elements:
856 604 528 287 321 Time Complexity (ms) for n = 5 is : 0.090071
Sorted Array (Merge Sort):
287 321 528 604 856
26
Design & Analysis of Algorithms Laboratory Manual
27
Design & Analysis of Algorithms Laboratory Manual
6. Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming
method (b) Greedy method.
import java.util.Scanner;
28
Design & Analysis of Algorithms Laboratory Manual
Output
Knapsack Problem - Dynamic Programming Solution:
Enter the max capacity of knapsack:
5
Enter number of objects:
4
Enter Weights:
1
2
2
1
Enter Profits:
15
20
10
12
Items =
4
2
1
Optimal solution = 47
29
Design & Analysis of Algorithms Laboratory Manual
import java.util.Scanner;
class KObject { // Knapsack object details
float w;
float p;
float r;
}
public class KnapsackGreedy {
static final int MAX = 20; // max. no. of objects
static int n; // no. of objects
static float M; // capacity of Knapsack
ReadObjects(obj);
Knapsack(obj);
scanner.close();
}
30
Design & Analysis of Algorithms Laboratory Manual
}
scanner.close();
}
Output
31
Design & Analysis of Algorithms Laboratory Manual
7. From a given vertex in a weighted connected graph, find shortest paths to other
vertices using Dijkstra's algorithm. Write the program in Java.
import java.util.*;
32
Design & Analysis of Algorithms Laboratory Manual
}
}
for (i = 1; i <= n; i++)
if (i != s)
System.out.println(i + ":" + d[i]);
}
Output
Enter the number of vertices:
5
Enter the cost adjacency matrix:
18
0 18 1 9999 9999 1 2
4
18 0 9999 6 4
1 9999 0 2 9999 5
1 6
9999 6 2 0 20
9999 4 9999 20 0
3
4 20
Enter starting vertex: 2
1
2:9
3:1
4:3
5:13
33
Design & Analysis of Algorithms Laboratory Manual
8. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal'salgorithm. Use Union-Find algorithms in your program.
import java.util.Scanner;
int i, j;
cost = new int[MAX][MAX];
34
Design & Analysis of Algorithms Laboratory Manual
35
Design & Analysis of Algorithms Laboratory Manual
Output
36
Design & Analysis of Algorithms Laboratory Manual
9. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Prim's algorithm.
import java.util.Scanner;
visited[1] = 1;
while (ne < n) {
for (i = 1, min = 999; i <= n; i++)
37
Design & Analysis of Algorithms Laboratory Manual
Output
Total cost: 70
38
Design & Analysis of Algorithms Laboratory Manual
import java.util.Scanner;
public class FloydsClass {
static final int MAX = 20; // max. size of cost matrix
static int a[][]; // cost matrix
static int n; // actual matrix size
39
Design & Analysis of Algorithms Laboratory Manual
Output
40
Design & Analysis of Algorithms Laboratory Manual
import java.util.Scanner;
41
Design & Analysis of Algorithms Laboratory Manual
temp[start + 1] = tour[i];
temp[i] = tour[start + 1];
if (c[tour[start]][tour[i]] + (cost = tspdp(c, temp, start + 1, n)) <
mincost) {
mincost = c[tour[start]][tour[i]] + cost;
for (k = 0; k < n; k++)
mintour[k] = temp[k];
}
}
for (i = 0; i < n; i++)
tour[i] = mintour[i];
return mincost;
}
}
Output
Travelling Salesman Problem using Dynamic Programming
Enter number of cities:
Enter cost matrix: 30
1 2
0 30 6 4
30 0 5 10 4
5
6 5 0 20 6 10
4 10 20 0
3 4
Minimum Tour Cost: 25 20
Tour:
0 -> 2 -> 1 -> 3 -> 0
42
Design & Analysis of Algorithms Laboratory Manual
11. Design and implement in Java 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.
import java.util.Scanner;
43
Design & Analysis of Algorithms Laboratory Manual
Output
Enter number of elements:
5
Enter the set in increasing order:
2
3
4
5
6
Enter the max. subset value(d): 9
2 3 4
3 6
4 5
44
Design & Analysis of Algorithms Laboratory Manual
12. Design and implement in Java to find all Hamiltonian Cycles in a connected
undirected Graph G of n vertices using backtracking principle.
import java.util.Scanner;
45
Design & Analysis of Algorithms Laboratory Manual
}
if (i == j)
G[i][j] = 0;
}
for (int i = 1; i <= n; i++)
x[i] = 0;
x[1] = 1;
scanner.close();
}
void HamiltonianMethod(int k) {
while (true) {
NextValue(k, G, x, n);
if (x[k] == 0)
return;
if (k == n) {
for (int i = 1; i <= k; i++)
System.out.print(x[i] + " ");
System.out.println(x[1]);
System.out.println();
found = true;
return;
} else
HamiltonianMethod(k + 1);
}
}
46
Design & Analysis of Algorithms Laboratory Manual
}
}
}
}
Output
Solution:
12341
3 4
13241
14231
47
Design & Analysis of Algorithms Laboratory Manual
Viva Questions:
1. What is an algorithm? What is the need to study Algorithms?
2. Explain Euclid’s Algorithm to find GCD of two integers with an e.g.
3. Explain Consecutive Integer Checking algorithm to find GCD of two numbers with an
e.g.
4. Middle School Algorithm with an e.g.
5. Explain the Algorithm design and analysis process with a neat diagram.
6. Define: a) Time Efficiency b) Space Efficiency.
7. What are the important types of problems that encounter in the area of computing?
8. What is a data structure? How are data structures classified?
9. Briefly explain linear and non-linear data structures.
10. What is a set? How does it differ from a list?
11. What are the different operations that can be performed on a set?
12. What are the different ways of defining a set?
13. How can sets be implemented in computer application?
14. What are different ways of measuring the running time of an algorithm?
15. What is Order of Growth?
16. Define Worst case, Average case and Best case efficiencies.
17. Explain the Linear Search algorithm.
18. Define O, Ω, Ө notations.
19. Give the general plan for analyzing the efficiency of non-recursive algorithms with an
e.g.
20. Give an algorithm to find the smallest element in a list of n numbers and analyze the
efficiency.
21. Give an algorithm to check whether all the elements in a list are unique or not and
analyze the efficiency
22. Give an algorithm to multiply two matrices of order N*N and analyze the efficiency.
23. Give the general plan for analyzing the efficiency of Recursive algorithms with an e.g.
24. Give an algorithm to compute the Factorial of a positive integer n and analyze the
efficiency.
25. Give an algorithm to solve the Tower of Hanoi puzzle and analyze the efficiency.
26. Define an explicit formula for the nth Fibonacci number.
27. Define a recursive algorithm to compute the nth Fibonacci number and analyze its
efficiency.
28. What is Exhaustive Search?
29. What is Traveling Salesmen Problem (TSP)? Explain with e.g.
30. Give a Brute Force solution to the TSP. What is the efficiency of the algorithm?
31. What is an Assignment Problem? Explain with an e.g.
32. Give a Brute Force solution to the Assignment Problem. What is the efficiency of the
algorithm?
33. Explain Divide and Conquer technique and give the general divide and conquer
recurrence.
34. Define: a)Eventually non-decreasing function b)Smooth function c)Smoothness rule
d)Masters theorem
35. Explain the Merge Sort algorithm with an e.g. and also draw the tree structure of the
recursive calls made.
36. Analyze the efficiency of Merge sort algorithm.
48
Design & Analysis of Algorithms Laboratory Manual
37. Explain the Quick Sort algorithm with an example and also draw the tree structure of
the recursive calls made.
38. Analyze the efficiency of Quick sort algorithm.
39. Give the Binary Search algorithm and analyze the efficiency.
40. Give an algorithm to find the height of a Binary tree and analyze the efficiency.
41. Give an algorithm each to traverse the Binary tree in Inorder, Preorder and Postorder.
42. Explain how do you multiply two large integers and analyze the efficiency of the
algorithm. Give an e.g.
43. Explain the Stassen’s Matrix multiplication with an e.g. and analyze the efficiency.
44. Explain the concept of Decrease and Conquer technique and explain its three major
variations.
45. Give the Insertion Sort algorithm and analyze the efficiency.
46. Explain DFS and BFS with an e.g. and analyze the efficiency.
47. Give two solutions to sort the vertices of a directed graph topologically.
48. Discuss the different methods of generating Permutations.
49. Discuss the different methods of generating Subsets.
50. What is Heap? What are the different types of heaps?
51. Explain how do you construct heap?
52. Explain the concept of Dynamic programming with an e.g.
53. What is Transitive closure? Explain how do you find out the Transitive closure with
an e.g.
54. Give the Warshall’s algorithm and analyze the efficiency.
55. Explain how do you solve the All-Pairs-Shortest-Paths problem with an e.g.
56. Give the Floyd’s algorithm and analyze the efficiency.
57. What is Knapsack problem? Give the solution to solve it using dynamic programming
technique.
58. What are Memory functions? What are the advantages of using memory functions?
59. Give an algorithm to solve the knapsack problem.
60. Explain the concept of Greedy technique.
61. Explain Prim’s algorithm with e.g.
62. Prove that Prim’s algorithm always yields a minimum spanning tree.
63. Explain Kruskal’s algorithm with an e.g.
64. Explain Dijkstra’s algorithm with an e.g.
65. What are Huffman trees? Explain how to construct a Huffman trees with an e.g.
66. Explain the concept of Backtracking with an e.g.
67. What is state space tree? Explain how to construct a state space tree?
68. What is n-Queen’s problem? Generate the state space tree for n=4.
69. Explain the subset sum problem with an e.g.
70. What are Decision Trees? Explain.
71. Define P, NP, and NP-Complete problems.
72. Explain the Branch and Bound technique with an e.g.
73. What are the steps involved in quick sort?
74. What is the principle used in the quick sort?
75. What are the advantages and disadvantages of quick sort?
76. What are the steps involved in merge sort?
77. What is divide, conquer, combine?
78. xplain the concept of topological ordering?
79. What are the other ordering techniques that you know?
80. How topological ordering is different from other ordering techniques?
49
Design & Analysis of Algorithms Laboratory Manual
50