DAA Labmanual 2022-23 4sem

Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

21CS42: Design and Analysis of Algorithms Laboratory

R N S Institute of Technology
RR Nagar Post, Bengaluru – 560 098.

Laboratory Manual
Academic Year March 2023 – June 2023

Programme B E – Artificial Intelligence and Machine Learning

Semester IV

Course Code 21CS42

DESIGN AND ANALYSIS OF ALGORITHMS


Course Title
LABORATORY

Smitha B A
Course Plan
Assistant Professor, Department of AI & ML
Author
RNS Institute of Technology, Bengaluru.

Dept. of AI&ML, RNSIT Page 1 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

21CS42: Design and Analysis of Algorithms Laboratory

Course Learning Objectives:


CLO 1. Explain the methods of analysing the algorithms and to analyze performance of
algorithms.
CLO 2. State algorithm’s efficiencies using asymptotic notations.
CLO 3. Solve problems using algorithm design methods such as the brute force method,
greedy method, divide and conquer, decrease and conquer, transform and conquer, dynamic
programming, backtracking and branch and bound.
CLO 4. Choose the appropriate data structure and algorithm design method for a specified
application.
CLO 5. Introduce P and NP classes.

Course outcome (Course Skill Set)


At the end of the course the student will be able to:
21CS42.1 Analyze the performance of the algorithms, state the efficiency using
asymptotic notations and analyze mathematically the complexity of the
algorithm.
21CS42.2 Apply divide and conquer approaches and decrease and conquer
approaches in solving the problems analyze the same.
21CS42.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.
21CS42.4 Apply and analyze dynamic programming approaches to solve some
problems. and improve an algorithm time efficiency by sacrificing space.
21CS42.5 Apply and analyze backtracking, branch and bound methods and to
describe P, NP and NP Complete problems.

CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
21CS42.1 3
21CS42.2 3
21CS42.3 3
21CS42.4 3

Dept. of AI&ML, RNSIT Page 2 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

Contents & Lab Conduction Plan


Date EXPERIMENT NAME Page No
Week
20/03 – 25/03 • Installation and Configuration of Android Studio 04
• Building “Namaste India!” App on AVD as well as on real device
Week - 1

27/03 - 01/04 Visiting Card – Mob App 05

Week - 2

03/04 – 08/04 Simple Calculator – Mob App 08

Week - 3

10/04 - 15/04 Login and signup – Mobile app 12

Week - 4
17/04/ -22/04 Changing Wallpaper - Mobile App 18

Week 5

24/04 -29/04 Project Synopsis Review

Week 6

01/05 – 06/05 Counter Application – Mobile App

Week 7

08/05 – 13/05 Parsing XML and JSON Data

Week 8

15/05 – 20/05 Text to Speech Application

Week 9

22/05 – 27/05 Call and Save Application

Week 10

29/05 – 03/06 Lab Internal Assessment

Week 11

06/06 – 12/06 Final Project Review

Week 12

Dept. of AI&ML, RNSIT Page 3 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

Dept. of AI&ML, RNSIT Page 4 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

Date Laboratory Conduction Plan


20/03 – 25/03 1. Demo of Installation and Configuration of Android
Week - 1 Studio
2. Creation and Deployment of “Namaste India” App

SYLLABUS

Modu
Program
le No
A. 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
1 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.

A. 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 B. 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.

A. Write & Execute C++/Java Program


1. To solve Knapsack problem using Greedy method.
2. To find shortest paths to other vertices from a given vertex in a weighted
connected graph, using Dijkstra's algorithm.
3 3. To find Minimum Cost Spanning Tree of a given connected undirected graph
using Kruskal's algorithm. Use Union-Find algorithms in your program.
4. To find Minimum Cost Spanning Tree of a given connected undirected graph
using Prim's algorithm.

A. Write C++/ Java programs to


1. Solve All-Pairs Shortest Paths problem using Floyd's algorithm.
4 2. Solve Travelling Sales Person problem using Dynamic programming.
3. Solve 0/1 Knapsack problem using Dynamic Programming method.

A. Design and implement C++/Java Program to find a subset of a given set S = {Sl,
5 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,

Dept. of AI&ML, RNSIT Page 5 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

8}. Display a suitable message, if the given problem instance doesn't have a
solution.
B. Design and implement C++/Java Program to find all Hamiltonian Cycles in a
connected undirected Graph G of n vertices using backtracking principle.

Sl.No Program List


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

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

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

Write & Execute C++/Java Program to solve Knapsack problem using Greedy method.
4
Write & Execute C++/Java Program to find shortest paths to other vertices from a given
5 vertex in a weighted connected graph, using Dijkstra's algorithm
Write & Execute C++/Java Program to find Minimum Cost Spanning Tree of a given
6 connected undirected graph using Kruskal's algorithm. Use Union-Find algorithms in your
program.
Write & Execute C++/Java Program to find Minimum Cost Spanning Tree of a given
7
connected undirected graph using Prim's algorithm.
Write C++/ Java programs to Solve All-Pairs Shortest Paths problem using Floyd's
8 algorithm.

Write C++/ Java programs to Solve Travelling Sales Person problem using Dynamic
9 programming.

Write C++/ Java programs to Solve 0/1 Knapsack problem using Dynamic Programming
10 method.

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 =
11 {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.

Dept. of AI&ML, RNSIT Page 6 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

Design and implement C++/Java Program to find all Hamiltonian Cycles in a connected
12 undirected Graph G of n vertices using backtracking principle.

Scheme of Evaluation
Assessment Details (both CIE and SEE)

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 Continuous
Internal Evaluation:

Three Unit Tests each of 20 Marks (duration 01 hour)

1. First test at the end of 5th week of the semester

2. Second test at the end of the 10th week of the semester

3. Third test at the end of the 15th week of the semester

Two assignments each of 10 Marks

4. First assignment at the end of 4th week of the semester

5. Second assignment at the end of 9th week of the semester

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.

• Viva-Voce– 5 Marks (more emphasized on demonstration topics)

The sum of three tests, two assignments, and practical sessions will be out of 100 marks and will
be scaled down to 50 marks

Course Outcome: (Course Skill Set)


At the end of the course the student will be able to:
CO 1: Analyze the performance of the algorithms, state the efficiency using asymptotic notations
and analyze 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.

Dept. of AI&ML, RNSIT Page 7 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

CO 5: Apply and analyze backtracking, branch and bound methods and to describe P, NP and
NPComplete problems

Dept. of AI&ML, RNSIT Page 8 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

JAVA Sample Programs


Example 1
JAVA program to print “Namaste! Welcome”.

public class Example1 {


public static void main(String[] args)
{

System.out.println(“Namaste! Welcome”);
}
}
OUTPUT :

Namaste! Welcome

Example 2
JAVA program to print Name, College and Place.

public class Example2 {


public static void main(String[] args) {
System.out.println("Name : Raghu");
System.out.println("College : RNSIT");
System.out.println("Place : Bengaluru");
}
}
OUTPUT :

Name : Raghu

College : RNSIT

Place : Bengaluru

Example 3
JAVA program to accept emp_name, emp_id, emp_salary and print them.
import java.util.Scanner;
public class Example3 {
public static void main(String[] args)
{ int mp_id;
String emp_name;
double emp_salary;
Scanner read = new Scanner(System.in);
System.out.println("Enter the employee name");

Dept. of AI&ML, RNSIT Page 9 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

emp_name=read.nextLine();

System.out.println("Enter the employee ID");


emp_id=read.nextInt();
System.out.println("Enter the employee salary");
emp_salary=read.nextDouble();
System.out.println("\nEntered details are");
System.out.println("Employee Name : "+emp_name);
System.out.println("Employee ID : "+emp_id);
System.out.println("Employee Salary : "+emp_salary);

}
}

OUTPUT :

Enter the employee name

Kushal
Enter the employee ID

46
Enter the employee salary

87000.50

Entered details are

Employee Name : Kushal


Employee ID : 46

Employee Salary : 87000.5

Example 4
JAVA program to perform mathematical operations on an expression.

import java.util.Scanner;
public class Example4 {
public static void main (String[] args)
{ double a,b,res=0;
char c;
Scanner read = new Scanner(System.in);
System.out.println("Enter the expression");
a=read.nextDouble();
c=read.next().charAt(0);
b=read.nextDouble();

Dept. of AI&ML, RNSIT Page 10 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

switch(c)

case '+' :
res=a+b;
break;
case '-' :
res=a-b;
break;
case '*' :
res=a*b;
break;
case '/' :
if(b==0)
{
System.out.println("Divide by zero error");
System.exit(0);

else
res=a/b;
break;

default :
System.out.println("Invalid Entry");
System.exit(0);
}

System.out.println("Result is : "+res);

}
OUTPUT :

Enter the expression

4 - 12
Result is : -8.0

Enter the expression

4.5 / 3

Result is : 1.5

Dept. of AI&ML, RNSIT Page 11 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

Enter the expression

5/0

Divide by zero error

Example 5
JAVA program to read and print array elements.

import java.util.Scanner;
public class Example5 {
public static void main(String[] args) { int []a = new int[10];
Scanner read = new Scanner(System.in);
System.out.println("Enter the array elements");
for(int i=0;i<a.length;i++)
a[i]=read.nextInt();
System.out.println("Entered array elements : ");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+"\t");
}
}
OUTPUT :

Enter the array elements


1324658790
Entered array elements :
1 3 2 4 6 5 8 7 9 0

Example 6
JAVA program to print array elements.

public class Example6 {


public static void main(String[] args) {
int []a = {1,2,3,4,5};
System.out.println("Entered array elements are");

for(int i=0;i<a.length;i++)

System.out.print(a[i]+"\t");
}

}
OUTPUT :
Entered array elements are

1 2 3 4 5

Dept. of AI&ML, RNSIT Page 12 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

Example 7
JAVA program to read n array elements and print the sum of array elements.

import java.util.Scanner;
public class Example7 {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int n,sum=0;

System.out.println("Enter the size of array ");

n=read.nextInt();

int []a=new int[n];

System.out.println("Enter the array elements");


for(int i=0;i<a.length;i++)
a[i]=read.nextInt();

for(int i=0;i<a.length;i++)

sum+=a[i];

System.out.println("Sum of array elements is "+sum);


}
}
OUTPUT :

Enter the size of array

4
Enter the array elements

2 6 7 22
Sum of array elements is 37

Example 8
JAVA program to read and print 2 x 2 matrix.

import java.util.Scanner;
public class Example8 {

public static void main(String[] args) {


Scanner read = new Scanner(System.in);
int [][]a = new int[2][2];
System.out.println("Enter the matrix");
for(int i=0;i<2;i++)

Dept. of AI&ML, RNSIT Page 13 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

for(int j=0;j<2;j++)

a[i][j]=read.nextInt();

System.out.println("Entered matrix is ");


for(int i=0;i<2;i++)

for(int j=0;j<2;j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
}
}
OUTPUT :
Enter the matrix

34 -12
44 90 Entered
matrix is
34 -12
44 90

Example 9
JAVA program to read and print M x N matrix.

import java.util.Scanner;
public class Example9 {
public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.println("Enter the number of rows");
int m = read.nextInt();
System.out.println("Enter the number of columns");
int n = read.nextInt();
int [][]a = new int[m][n];
System.out.println("Enter the matrix"); for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
a[i][j]=read.nextInt();

System.out.println("Entered matrix is ");

for(int i=0;i<m;i++)
{

for(int j=0;j<n;j++)
System.out.print(a[i][j]+"\t");

Dept. of AI&ML, RNSIT Page 14 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

System.out.println();
}
}

}
OUTPUT :
Enter the number of rows
3
Enter the number of columns
3
Enter the matrix
12 56 4
7 13 -3
77 14 6
12 56 4
7 13 -3
77 14 6

Example 10
JAVA program to print 2 x 2 matrix.

public class Example10 {


public static void main(String[] args) {
int [][]a = {{1,2},{3,4}};
System.out.println("Entered matrix is ");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
System.out.print(a[i][j]+"\t");

System.out.println();
}
}
}

OUTPUT :

Entered matrix is

1 2
3 4

Example 11
JAVA program to find the biggest element in the given M x N matrix.

import java.util.Scanner;

Dept. of AI&ML, RNSIT Page 15 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

public class Example11


{
public static void main(String[] args)
{
Scanner read=new Scanner(System.in);
System.out.println("Enter the number of rows");
int m=read.nextInt();
System.out.println("Enter the number of columns");
int n=read.nextInt();
int[][] a=new int[m][n];
System.out.println("Enter the matrix");
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
a[i][j]=read.nextInt();
int big=a[0][0];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(a[i][j]>big)
big=a[i][j];
}
}
System.out.println("The biggest element in the matrix is "+big);
}
}
OUTPUT :
Enter the matrix
4 8
3 9
The biggest element in the matrix is 9

Example 12
JAVA program to print volume using an object.

class Box1
{
double width,height,depth;
}
public class Example12
{
public static void main(String[] args)

{
Box1 b1=new Box1();
b1.height=10;
b1.width=20;
b1.depth=30;

Dept. of AI&ML, RNSIT Page 16 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

double vol=b1.height* b1.width* b1.depth;


System.out.println("Volume is "+vol);

}
}
OUTPUT :

Volume is 6000.0

LAB Programs

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.

ALGORITHM:

ALGORITHM SelectionSort(A[l...r]) //Sorts subarray by selectionsort


Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted

Program:
import java.util.Random;

public class SelectionSort {

public static void selectionSort(int[] arr) {


int n = arr.length;

for (int i = 0; i < n-1; i++) {


int min_idx = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

Dept. of AI&ML, RNSIT Page 17 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

public static void main(String[] args) {


int[] arr = new int[5000];
Random rand = new Random();

// generate random array of size 5000


for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(10000);
}

// measure time complexity for various array sizes


for (int n = 5000; n <= 50000; n += 5000) {
int[] testArr = new int[n];

// generate random array of size n


for (int i = 0; i < n; i++) {
testArr[i] = rand.nextInt(10000);
}

long startTime = System.nanoTime();


selectionSort(testArr);
long endTime = System.nanoTime();

long duration = (endTime - startTime) / 1000000; // convert to milliseconds

System.out.println("Array size: " + n + " | Time taken: " + duration + "ms");


}
}
}

Output:
Array size: 5000 | Time taken: 15ms
Array size: 10000 | Time taken: 63ms
Array size: 15000 | Time taken: 142ms
Array size: 20000 | Time taken: 256ms
Array size: 25000 | Time taken: 394ms
Array size: 30000 | Time taken: 565ms
Array size: 35000 | Time taken: 768ms
Array size: 40000 | Time taken: 1006ms
Array size: 45000 | Time taken: 1281ms
Array size: 50000 | Time taken: 1592ms

The above code first generates a random array of size 5000 using the Random class. It
then measures the time taken to sort arrays of various sizes ranging from 5000 to 50000 in
steps of 5000 using System.nanoTime(). The time taken is then printed to the console.

To analyze the time complexity, we can look at the number of comparisons and swaps
made by the algorithm. In the worst case, Selection Sort makes n-1 comparisons and n-1
swaps, giving it a time complexity of O(n^2). In the best case, if the array is already

Dept. of AI&ML, RNSIT Page 18 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

sorted, it makes n-1 comparisons and 0 swaps, giving it a time complexity of O(n). In the
average case, it still makes n-1 comparisons and swaps, giving it a time complexity of
O(n^2).

2. 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 non 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.

ALGORITHM:
ALGORITHM Quicksort(A[l...r]) //Sorts 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 non decreasing order If l<r

s ← Partition(A[l...r]) //s is a split position

Quicksort(A[l...s-1])

Quicksort(B[s+1...r])

ALGORITHM Partition(A[l...r])
//Partitions a subarray by using its first element as a 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
repeat j ← j-1 until A[j] ≤ p
swap(A[i], A[j])

until i ≥ j

swap(A[i], A[j]) //undo last swap when i ≥ j swap(A[l], A[j])

return j

import java.util.Random;
import java.util.Scanner;

public class Main

Dept. of AI&ML, RNSIT Page 19 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

{
/* function that consider last element as pivot,
place the pivot at its exact position, and place
smaller elements to left of pivot and greater
elements to right of pivot. */
public static int partition (int a[], int start, int end)
{
int pivot = a[end]; // pivot element
int i = (start - 1);

for (int j = start; j <= end - 1; j++)


{
// If current element is smaller than the pivot
if (a[j] < pivot)
{
i++; // increment index of smaller element
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
}

/* function to implement quick sort */


public static void quick(int a[], int start, int end)
/* a[] = array to be sorted, start = Starting index, end = Ending index */
{
if (start < end)
{
int p = partition(a, start, end); //p is partitioning index
quick(a, start, p - 1);
quick(a, p + 1, end);
}
}

/* function to print an array */


void printArr(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
System.out.print(a[i] + " ");
}

/*public static void main(String[] args) {


int a[] = { 13, 18, 27, 2, 19, 25 };

Dept. of AI&ML, RNSIT Page 20 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

int n = a.length;
System.out.println("\nBefore sorting array elements are - ");
Main q1 = new Main();
q1.printArr(a, n);
q1.quick(a, 0, n - 1);
System.out.println("\nAfter sorting array elements are - ");
q1.printArr(a, n);
System.out.println();
}
*/
public static void main(String[] args)
{
int a[]= new int[100000];

Scanner in = new Scanner(System.in);


long start, end;
System.out.println("*********QUICK SORT PROGRAM******");
System.out.println("Enter the number of elements to be sorted");
int n = in.nextInt();
Random rand= new Random();
//System.out.println("Enter the elements : ");
for(int i=0;i<n;i++)
{
a[i]=rand.nextInt(10000);
// a[i]=in.nextInt();
}
System.out.println("Array elements to be sorted are : ");
for(int i=0; i<n; i++)
System.out.println(a[i]+" ");

//a[n]=9999;
start=System.currentTimeMillis();
quick(a,0,n-1);
end=System.currentTimeMillis();

System.out.println("\nThe sorted elements are : ");

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


System.out.println(a[i]+" ");

System.out.println("\nThe time taken to sort is "+(end-start)+"ms");


System.out.println("******** ******************* *******");
}

Output1
*********QUICK SORT PROGRAM *********
Enter the number of elements to be sorted

Dept. of AI&ML, RNSIT Page 21 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

5000
Array elements to be sorted are :
1045
6967
7672
3119
…..
The sorted elements are :
3
4
7
8
…..
The time taken to sort is 3133233ns
******** ******************* *******
Output 2:
*********QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
6000
Array elements to be sorted are:
948
1527
360

The sorted elements are:
2
5
8
11
12
13
13
14
..
The time taken to sort is 2647573ns
******** ******************* *******
OUPUT 3:
*********QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
20
Enter the elements:
1
2
3
4

20
The sorted elements are:
1

Dept. of AI&ML, RNSIT Page 22 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

2
3
4
….
20
The time taken to sort is 28925ns
******** ******************* *******

OUTPUT 4
*********QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
20
Enter the elements:
20
18
18
16
….
2
1
The sorted elements are:
1
2
3
4

18
20
The time taken to sort is 32657ns
******** ******************* *******
Output 5:
*********QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
20
Enter the elements:
4
6
7
9
2
13
16
18
19
7
11
15
9
10

Dept. of AI&ML, RNSIT Page 23 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

16
23
34
12
4
7

The sorted elements are:


2
4
4
6
7
7
7
9
9
10
11
12
13
15
16
16
18
19
23
34
The time taken to sort is 35457ns
******** ******************* *******

Dept. of AI&ML, RNSIT Page 24 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

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

ALGORITHM :

ALGORITHM Mergesort(A[0...n-1])

//Sorts array A[0..n-1] by recursive mergesort


//Input: An array A[0...n-1] of orderable elements
//Output: Array A[0...n-1] sorted in non decreasing order If n>1
copy A[0...⌊ /2⌋-1] to B[0... ⌊ /2⌋-1]
copy A[ ⌊ /2⌋...n-1] to C[⌈ /2⌉...-1]
Mergesort(B[0... ⌊ /2⌋-1])
Mergesort(C[0...⌈ /2⌉-1])

Merge(B, C, A)

ALGORITHM Merge(B[0...p-1], C[0...q-1], A[0...p+q-1])


//Merges two sorted array into one sorted array
//Input: Arrays B[0...p-1] and C[0...q-1] both sorted //Output: Sorted array A[0...p+q-
1]of the elements of B and C i ← 0; j ← 0; k ← 0

while i < p and j < q do

if B[i]≤ C[j]

A[k] ← B[i]; i ← i+1

else A[k] ← C[j]; j ← j+1

k ← k+1

if i = p
copy C[j...q-1] to A[k...p+q-1]

else

copy B[i...p-1] to A[k...p+q-1]

import java.util.Scanner;
import java.util.Random;

class Main {

/* Function to merge the subarrays of a[] */

Dept. of AI&ML, RNSIT Page 25 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

public static void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;

/* temporary Arrays */
int LeftArray[] = new int[n1];
int RightArray[] = new int[n2];

/* copy data to temp arrays */


for (i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];

i = 0; /* initial index of first sub-array */


j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */

while (i < n1 && j < n2)


{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}

while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}

Dept. of AI&ML, RNSIT Page 26 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

public static void mergeSort(int a[], int beg, int end)


{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}

/* Function to print the array */


void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
System.out.print(a[i] + " ");
}

/*public static void main(String args[])


{
int a[] = { 11, 30, 24, 7, 31, 16, 39, 41 };
int n = a.length;
Main m1 = new Main();
System.out.println("\nBefore sorting array elements are - ");
m1.printArray(a, n);
m1.mergeSort(a, 0, n - 1);
System.out.println("\nAfter sorting array elements are - ");
m1.printArray(a, n);
System.out.println("");
} */

public static void main(String[] args)


{
int a[]= new int[100000];

Scanner in = new Scanner(System.in);


long start, end;
System.out.println("****** MERGE SORT PROGRAM *******");

System.out.println("Enter the number of elements to be sorted");


int n = in.nextInt();
Random rand= new Random();
for(int i=0;i<n;i++)
a[i]=rand.nextInt(10000);
System.out.println("Array elements to be sorted are : ");
for(int i=0; i<n; i++)
System.out.println(a[i]+" ");

Dept. of AI&ML, RNSIT Page 27 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

start=System.currentTimeMillis();
mergeSort(a,0,n-1);
end=System.currentTimeMillis();
System.out.println("\nThe sorted elements are : ");
for(int i=0; i<n; i++)
System.out.println(a[i]+" ");

System.out.println("\nThe time taken to sort is "+(end-start)+" ms");


System.out.println("******** ********************** *******");
}

Output 1: ********** MERGE SORT PROGRAM *********


Enter the number of elements to be sorted
5000
Array elements to be sorted are :
3189
1841
3160
8740

The sorted elements are :
3
4
5
6
7
11
20
…..
The time taken to sort is 1173776857 ns
******** ********************** *******

Output 2:
********** MERGE SORT PROGRAM *********
Enter the number of elements to be sorted
6000
Array elements to be sorted are :
2853
3407
8435
8882
3709

The sorted elements are :
0
0
1

Dept. of AI&ML, RNSIT Page 28 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

1
1
….
The time taken to sort is 1256530873 ns
******** ********************** *******

4. Write & Execute C++/Java Program. To solve Knapsack problem using Greedy
method.

ALGORITHM GreedyKnapsack(float m, int n)


//P[1:n] and w[1:n] contain the profits and weights respectively of the n objects

// ordered such that P[i]/w[i] ≥ P[i+1]/w[i+1]. m is the knapsack size and x[1:n] is

// the solution vector


{

for (int i = 1; i ≤ n; i++)

x[i] = 0.0; //Initialize x

float u = m;

for (i = 1; i ≤ n; i++) {

Dept. of AI&ML, RNSIT Page 29 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

if (w[i] > u) continue;


x[i] = 1.0;

u - = w[i];

}
}

Greedy method.
import java.util.Scanner;
class GreedyKnapsack
{
private int n;
private int m;
//private int[][] array;
private int [] w;
private int [] p;

public GreedyKnapsack(int n, int m, int[] w, int[] p)


{
this.n=n;
this.m=m;
this.w=w;
this.p=p;
}

public void greedy()


{
float sum=0,max;
int i,j=0;
while(m>=0)
{
max=0;
for(i=0;i<n;i++)
{
if(((float)p[i])/((float)w[i])>max)
{
max=((float)p[i])/((float)w[i]);
j=i;
}
}
if(w[j]>m)
{
System.out.println("Quantity of item number: " +
(j+1) + "
added is " +(float)m/w[j]);
sum = sum + m*max;
m = -1;
}
else
{
System.out.println("Quantity of item number: " + (j+1) + "
Dept. of AI&ML, RNSIT Page 30 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

added fully ");


/* + array[0][j]);*/
m = m - w[j];
sum = sum + (float)p[j];
p[j]=0;
}
}
System.out.println("The total profit is : " + sum);
}
}
public class knapsack
{
public static void main(String[] args)
{
int i,max_qty,m,n;
Scanner sc = new Scanner(System.in);
// int array[][]=new int[2][20];
int w[] = new int[10];
int p[] = new int[10];
System.out.println("Enter no of items : ");
n=sc.nextInt();

System.out.println("Enter the weights of each items : ");


for(i=0;i<n;i++)
w[i]=sc.nextInt();

System.out.println("Enter the profit of each items : ");


for(i=0;i<n;i++)
p[i]=sc.nextInt();

System.out.println("Enter the knapsack capacity : ");


max_qty=sc.nextInt();

m=max_qty;

GreedyKnapsack gks = new GreedyKnapsack(n, m, w, p);


gks.greedy();
sc.close();
}
}

OUTPUT

Enter no of items :
3
Enter the weights of each items :
18
15
10
Enter the profit of each items :
25
24
15
Enter the knapsack capacity :
Dept. of AI&ML, RNSIT Page 31 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

20
Quantity of item number: 2 added fully
Quantity of item number: 3 added is 0.5
The total profit is : 31.5

5. Write & Execute C++/Java Program, to find shortest paths to other vertices from a given vertex
in a weighted connected graph, using Dijkstra's algorithm.

ALGORITHM :
ALGORITHM Dijkstra(G)

// Dijkstra’s algorithm for single-source shortest paths

// Input: A weighted connected graph G = <V, E> with

// non negative weights and its vertex s

// Output: The length dv of a shortest path from s to v and its


// penultimate vertex pv for every vertex v in V

Initialize(Q) //initialize vertex priority queue to empty


for every vertex v in V do
dv ← ∞; pv ← null
Insert(Q, v, dv)
//initialize vertex priority in the priority queue

ds ← 0; Decrease(Q, s, ds) //update priority of s with ds


VT ← Ø

for i ← 0 to |V| - 1 do

u* ← DeleteMin(Q) //delete the minimum priority element


VT ← VT U {u*}
for every vertex u in V – VT that is adjacent to u* do
if du* + w(u*, u) < du

du ← du* + w(u*, u); pu ← u*


Decrease(Q, u, du)

import java.util.*;
public class dijkstra
{
public static void main(String[] args)
{
int i, j;

int dist[]=new int[10], visited[]=new int[10];


int cost[][]=new int[10][10], path[]=new int[10];

Scanner in = new Scanner(System.in);

System.out.println("**** DIJKSTRA'S ALGORITHM ******");


Dept. of AI&ML, RNSIT Page 32 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

System.out.println("Enter the number of nodes: ");


int n = in.nextInt();

System.out.println("Enter the cost matrix");


for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cost[i][j] = in.nextInt();

System.out.println("The entered cost matrix is");


for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(cost[i][j]+"\t");
}
System.out.println();
}

System.out.println("Enter the source vertex: ");


int sv = in.nextInt();

dij(cost,dist,sv,n,path,visited);
printpath(sv,n,dist,path,visited );

System.out.println("\n********* *************** *********");


}
static void dij(int cost[][],int dist[],int sv,int n,int path[],int visited[])
{
int count = 2,min,v=0;

for(int i=1; i<=n; i++)


{
visited[i]=0;
dist[i] = cost[sv][i];

if(cost[sv][i] == 999)
path[i] = 0;
else
path[i] = sv;
}

visited[sv]=1;

while(count<=n)
{
min = 999;
for(int w=1; w<=n; w++)
if((dist[w]< min) && (visited[w]==0))
{
min = dist[w];
v = w;
}

Dept. of AI&ML, RNSIT Page 33 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

visited[v] = 1;
count++;

for(int w=1; w<=n; w++)


{
if((dist[w]) >(dist[v] + cost[v][w]))
{
dist[w] = dist[v] + cost[v][w]; path[w] = v;
}
}
}
}

static void printpath(int sv,int n,int dist[],int path[], int visited[])


{
for(int w=1; w<=n; w++)
{
if(visited[w] == 1 && w != sv)
{
System.out.println("The shortest distance between ");
System.out.println(sv+"-> ="+w+" is :"+ dist[w]);

int t=path[w];
System.out.println("The path is:");
System.out.print(" "+w);

while(t != sv)
{
System.out.print("<-->"+t);
t=path[t];
}
System.out.print("<-->"+sv);
}
}
}
}

OUTPUT
**** DIJKSTRA'S ALGORITHM ******
Enter the number of nodes:
5
Enter the cost matrix
999 3 999 7 999
3 999 4 2 999
999 4 999 5 6
7 2 5 999 4
999 999 6 4 999
The entered cost matrix is
999 3 999 7 999
3 999 4 2 999
999 4 999 5 6
7 2 5 999 4
999 999 6 4 999
Enter the source vertex:
Dept. of AI&ML, RNSIT Page 34 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

1
The shortest distance between
1-> =2 is :3
The path is:
2<-->1The shortest distance between
1-> =3 is :7
The path is:
3<-->2<-->1The shortest distance between
1-> =4 is :5
The path is:
4<-->2<-->1The shortest distance between
1-> =5 is :9
The path is:
5<-->4<-->2<-->1
********* *************** *********

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

ALGORITHM :
ALGORITHM 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 //initialize the set of tree edges and its size k ← 0
while ecounter < |V| - 1 do
k ← k+1
if ET U {eik} is acyclic
ET ← ET U {eik}; ecounter ← ecounter + 1
return ET

import java.util.Scanner;
public class kruskalUnion
{
static int [] parent =new int [50];
static int [][]cost = new int [10][10];
static int a,b,i,j,u,v,n,min,noe=1,mincost=0;

static int find(int w)


{
while(parent[w]!=0)
w=parent[w];
return w;
}
static void union()
{
if(u!=v)
{
noe++;
Dept. of AI&ML, RNSIT Page 35 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

System.out.println(noe-1 + "Edge("+a+","+b+")="+min);
mincost+=min;
parent[v]=u;
}
cost[a][b]=cost[b][a]=999;
}

public static void main(String[] args)


{
Scanner read = new Scanner(System.in);
System.out.println("Enter the no. of vertices:");
n=read.nextInt();

System.out.println("Enter the cost adjacency matrix, 999 for no direct path:");

for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cost[i][j]=read.nextInt();

while(noe<n)
{
min=999;
for(i=1; i<=n ; i++)
{
for(j=1; j<=n; j++)
{
if(cost[i][j] < min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
union();
}
System.out.println("minimum cost ="+mincost);
}
}
OUTPUT:

Enter the no. of vertices:


6
Enter the cost adjacency matrix, 999 for no direct path:
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
1Edge(2,3)=1
2Edge(5,6)=2
Dept. of AI&ML, RNSIT Page 36 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

3Edge(1,2)=3
4Edge(2,6)=4
5Edge(4,6)=5
minimum cost =15

7. Write & Execute C++/Java Program, to find Minimum Cost Spanning Tree of a given
connected undirected graph using Prim's algorithm

import java.util.*;
public class prims
{
public static void main(String[] args)
{
int cost[][]=new int[10][10];
int i, j, mincost = 0;

Scanner in = new Scanner(System.in);


System.out.println("********* PRIMS ALGORITHM *********");

System.out.println("Enter the number of nodes");


int n = in.nextInt();

System.out.println("Enter the cost matrix");


for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
cost[i][j] = in.nextInt();
}
}

System.out.println("The entered cost matrix is");


for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
System.out.print(cost[i][j]+"\t");
}
System.out.println();
}

System.out.println("Minimum Spanning Tree Edges and costs are : ");

mincost=pr(cost,n,mincost);

System.out.println("The minimum spanning tree cost is : " +mincost);

System.out.println("******* ********************* *******");


}

static int pr(int cost[][],int n,int mincost)


{
int nearV[]=new int[10],t[][]=new int[10][3],u = 0,i,j,k;
Dept. of AI&ML, RNSIT Page 37 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

for(i=2; i<=n; i++)


nearV[i]=1;

nearV[1]=0;
for(i=1; i<n; i++)
{
int min=999;
for(j=1;j<=n;j++)
{
if(nearV[j]!=0 && cost[j][nearV[j]]<min)
{
min=cost[j][nearV[j]];
u=j;
}
}
t[i][1] = u;
t[i][2] = nearV[u];
mincost += min;
nearV[u] = 0;

for(k=1; k<=n; k++)


{
if(nearV[k] != 0 && cost[k][nearV[k]] > cost[k][u])
nearV[k] = u;
}

System.out.println(i+ " Minimum edge is " + t[i][1] + "," + t[i][2] + "


and its
cost is :"+min);
}
return mincost;
}
}

OUTPUT
********* PRIMS ALGORITHM *********
Enter the number of nodes
6
Enter the cost matrix
999 3 999 999 6 5
3 999 1 999 999 4
999 1 999 5 999 4
999 999 5 999 8 5
6 999 999 8 999 2
5 4 4 5 2 999
The entered cost matrix is
999 3 999 999 6 5
3 999 1 999 999 4
999 1 999 5 999 4
999 999 5 999 8 5
6 999 999 8 999 2
5 4 4 5 2 999
Minimum Spanning Tree Edges and costs are :
Dept. of AI&ML, RNSIT Page 38 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

1 Minimum edge is 2,1 and its cost is :3


2 Minimum edge is 3,2 and its cost is :1
3 Minimum edge is 6,2 and its cost is :4
4 Minimum edge is 5,6 and its cost is :2
5 Minimum edge is 4,3 and its cost is :5
The minimum spanning tree cost is : 15
******* ********************* *******

8. Write C++/ Java programs to, Solve All-Pairs Shortest Paths problem using Floyd's
algorithm.

Floyd's algorithm.

ALGORITHM :
ALGORITHM Floyd( W[1...n, 1...n] )
// Implement Floyd’s algorithm for 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 path’s 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

import java.util.Scanner;
public class floyd
{
public static void main(String[] args)
{
int a[][]=new int[10][10];
int i, j;

Scanner in = new Scanner(System.in);


System.out.println("***********FLOYD'SALGORITHM**********");

System.out.println("Enter the number of vertices: ");


int n = in.nextInt();

System.out.println("Enter the adjacency matrix");


for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
a[i][j] = in.nextInt();

System.out.println("Entered adjacency matrix is: ");

for(i=1;i<=n;i++)
{
for(j=1; j<=n; j++)
{
System.out.print(a[i][j]+"\t");
Dept. of AI&ML, RNSIT Page 39 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

}
System.out.println();
}

floydalgo(a,n);

System.out.println("All pair shortest path matrix:");

for (i=1; i<=n; i++)


{
for (j=1; j<=n; j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
System.out.println("************ ********* **************");
}

static void floydalgo(int a[][],int n)


{
for (int k=1; k<=n; k++)
{
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
a[i][j] = min(a[i][j], a[i][k] + a[k][j]);
}
}

static int min(int a,int b)


{
if(a>b)
return b;
else
return a;
}
}

OUTPUT:

***********FLOYD'SALGORITHM**********
Enter the number of vertices:
4
Enter the adjacency matrix
0 999 3 999
2 0 999 999
0701
6 999 999 0
Entered adjacency matrix is:
0 999 3 999
2 0 999 999
0 7 0 1
6 999 999 0
All pair shortest path matrix:
0 10 3 4
2 0 5 6
Dept. of AI&ML, RNSIT Page 40 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

0 7 0 1
6 16 9 0
************ ********* **************

9. Write C++/ Java programs to Solve Travelling Sales Person problem using Dynamic
programming.

Travelling Sales Person problem using Dynamic programming

import java.util.*;
import java.util.Scanner;

public class travel {


public static void main(String[] args)
{
int c[][]=new int[10][10], tour[]=new int[10];

Scanner in = new Scanner(System.in);

int i, j,cost;
System.out.println("**** TSP DYNAMIC PROGRAMMING *******");

System.out.println("Enter the number of cities: ");


int n = in.nextInt();

if(n==1)
{
System.out.println("Path is not possible");
System.exit(0);
}

System.out.println("Enter the cost matrix");


for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
c[i][j] = in.nextInt();

System.out.println("The entered cost matrix is");

for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println();
}

for(i=1;i<=n;i++)
tour[i]=i;

cost = tspdp(c, tour, 1, n);

System.out.println("The accurate path is");


Dept. of AI&ML, RNSIT Page 41 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

for(i=1;i<=n;i++)
System.out.print(tour[i]+"->");

System.out.println("1");

System.out.println("The accurate mincost is "+cost);


System.out.println("******* ************* ***************");
}

static int tspdp(int c[][], int tour[], int start, int n)


{
int mintour[]=new int[10], temp[]=new int[10], mincost=999, ccost, i, j, k;
if(start == n-1)
{
return (c[tour[n-1]][tour[n]] + c[tour[n]][1]);
}

for(i=start+1; i<=n; i++)


{
for(j=1; j<=n; j++)
temp[j] = tour[j];

temp[start+1] = tour[i];
temp[i] = tour[start+1];

if((c[tour[start]][tour[i]]+(ccost=tspdp(c,temp,start+1,n)))<mincost)
{
mincost = c[tour[start]][tour[i]] + ccost;

for(k=1; k<=n; k++)


mintour[k] = temp[k];
}
}
for(i=1; i<=n; i++)
tour[i] = mintour[i];

return mincost;
}
}

**** TSP DYNAMIC PROGRAMMING *******


Enter the number of cities:
4
Enter the cost matrix
0 10 15 20
5 0 9 10
6 13 0 12
8890
The entered cost matrix is
0 10 15 20
5 0 9 10
6 13 0 12
8 8 9 0
Dept. of AI&ML, RNSIT Page 42 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

The accurate path is


1->2->4->3->1
The accurate mincost is 35
******* ************* ***************

10. Write C++/ Java program to, to solve Knapsack problem using Dynamic
Programming method

ALGORITHM :

ALGORITHM MFKnapsack(i, j)
// Implements the memory function method for the knapsack problem
// Input: A nonnegative integer i indicating the number of the first items being

// considered and a nonnegative integer j indicating the knapsack’s capacity


// Output: The value of an optimal feasible subset of the first i items
// Note: Uses as global variables input arrays Weights[1..n], Values[1..n], and table

// V[0..n, 0..W] whose entries are //initialized with -1’s except for row 0 and column 0

// initialized with 0’s

if V[i, j] < 0
if j < Weights[i]
value ← MFKnapsack(i – 1, j)

else
value ← max(MFKnapsack(i – 1, j), Values[i] +
MFKnapsack(i – 1, j-Weights[i]))
V[i, j] ← value
return V[i, j]

Dept. of AI&ML, RNSIT Page 43 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

import java.util.Scanner;
public class knap
{
public static void main(String[] args)
{
int v[][]=new int[30][30], w[]=new int[10], p[]=new int[10];
Scanner in = new Scanner(System.in);
int i, j;

System.out.println("******** KNAPSACK PROBLEM ***********");

System.out.println("Enter the total number of items: ");


int n = in.nextInt();

System.out.println("Enter the weight of each item: ");


for(i=1;i<=n;i++)
w[i] = in.nextInt();

System.out.println("Enter the profit of each item: ");


for(i=1;i<=n;i++)
p[i] = in.nextInt();

System.out.println("Enter the knapsack capacity: ");


int m= in.nextInt();

displayinfo(m,n,w,p);
knapsack(m,n,w,p,v);

System.out.println("The contents of the knapsack table are");


for(i=0; i<=n; i++)
{
for(j=0; j<=m; j++)
{
System.out.print(v[i][j]+" " );
}
System.out.println();
}
optimal(m,n,w,v);
}

static void displayinfo(int m,int n,int w[],int p[])


{
System.out.println("Entered information about knapsack problem are");

System.out.println("ITEM\tWEIGHT\tPROFIT");
for(int i=1; i<=n; i++)
System.out.println(i+"\t"+w[i]+"\t"+p[i]);
System.out.println("Capacity = "+m);
}

static void knapsack(int m,int n,int w[],int p[],int v[][])


{

Dept. of AI&ML, RNSIT Page 44 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

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


{
for(int j=0; j<=m; j++)
{
if(i==0 ||j==0)
v[i][j]=0;
else if(j < w[i])
v[i][j]=v[i-1][j];
else
v[i][j]=max(v[i-1][j], v[i-1][j-w[i]]+p[i]);
}
}
}

private static int max(int i, int j)


{
if(i>j)
return i;
else
return j;
}

static void optimal(int m,int n,int w[],int v[][])


{
int i = n, j = m, item=0;
int x[]=new int[10];
while( i != 0 && j != 0)
{
if(v[i][j] != v[i-1][j])
{
x[i] = 1;
j = j-w[i];
}
i = i-1;
}
System.out.println("Optimal solution is :"+ v[n][m]);
System.out.println("Selected items are: ");
for(i=1; i<= n;i++)
if(x[i] == 1)
{
System.out.print(i+" ");
item=1;
}

if(item == 0)
System.out.println("NIL\t Sorry ! No item can be placed in Knapsack");
System.out.println("\n***************************************");
}
}

OUTPUT
************* KNAPSACK PROBLEM ***********

Dept. of AI&ML, RNSIT Page 45 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

Enter the total number of items:


3
Enter the weight of each item:
18
15
10
Enter the profit of each item:
25
24
15
Enter the knapsack capacity:
20
Entered information about knapsack problem are
ITEM WEIGHT PROFIT
1 18 25
2 15 24
3 10 15
Capacity = 20
The contents of the knapsack table are
000000000000000000000
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 25 25 25
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 24 24 24 25 25 25
0 0 0 0 0 0 0 0 0 0 15 15 15 15 15 24 24 24 25 25 25
Optimal solution is :25
Selected items are:
1
********* *********************** *************

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

ALGORITHM :
void SumOfSub (float s, int k, float r)

// Find all subsets of w[1:n] that sum to m. The values of x[j], 1<=j<k, have already

// Generate left child. Note that s+w[k] <=m


// because Bk-1 is true.

x[k] =1;

if (s+w[k] == m)

{// Subset found

for (int j=1; j<=k; j++) cout << x[j] << ‘ ‘ ;


cout << end1;

Dept. of AI&ML, RNSIT Page 46 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

// There is no recursive call here

// as w[j] > 0, 1 <= j <= n.

else if (s+w[k]+w[k+1] <= m)

SumOfSub(s+w[k], k+1, r-w[k]);


// Generate right child and evaluate Bk .

if ((s+r-w[k] >= m) && (s+w[k+1] <= m)) {

x[k] = 0;

SumOfSub(s, k+1, r-w[k]);

import java.util.Scanner;
public class subset
{
static int c=0;
public static void main(String[] args)
{
int w[]=new int[10];

int n, d, i, sum=0; int x[]=new int[10];

Scanner in=new Scanner(System.in);


System.out.println("********** SUBSET PROBLEM ************");

System.out.println("Enter the number of elements: ");


n=in.nextInt();

System.out.println("Enter the elements in increasing order");


for(i=0;i<n;i++)
w[i]=in.nextInt();

System.out.println("Enter the value of d: ");


d=in.nextInt();

for(i=0;i<n;i++)
sum=sum+w[i];

System.out.println("SUM ="+sum);

Dept. of AI&ML, RNSIT Page 47 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

if(sum < d || w[0] > d)


{
System.out.println("Subset is not possible ! ");
System.out.println("********** *********** *************");
System.exit(0);
}

finalsubset(0,0,sum,x,w,d);
if(c==0)
System.out.println("Subset is not possible ! ");

System.out.println("\n********** ********* *************");


}

static void finalsubset(int cs, int k, int r,int x[],int w[],int d)


{
x[k] = 1;

if(cs+w[k] == d)
{
c++;
System.out.print("\nSolution "+c+" is {");

for(int i=0;i<=k;i++)
if(x[i] == 1)
{
System.out.print(w[i]+" ");
}
System.out.print("}");
}
else if((cs + w[k] + w[k+1]) <= d)
finalsubset(cs + w[k], k+1, r-w[k],x,w,d);

if((cs + r - w[k]) >= d && (cs + w[k+1]) <= d)


{
x[k] = 0;
finalsubset(cs, k+1, r-w[k],x,w,d);
}
}
}

OUTPUT
********** SUBSET PROBLEM ************
Enter the number of elements:
5
Enter the elements in increasing order
12568
Enter the value of d:
9
SUM =22

Solution 1 is {1 2 6 }

Dept. of AI&ML, RNSIT Page 48 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

Solution 2 is {1 8 }
********** ********* *************
12. Design and implement C++/Java Program to find all Hamiltonian Cycles in a
connected undirected Graph G of n vertices using backtracking principle.

ALGORITHM :
void Hamiltonian (int k)

// This program uses the recursive formulation of backtracking to find all

// the Hamiltonian cycles of a graph. The graph is stored as an adjacency

// matrix G[1:n] [1:n]. All cycles begin at node 1.

do { // Generate values for x[k].

NextValue(k) ; // Assign a legal next value to x[k].

if (!x[k]) return;

if (k == n) {

for (int i=1; i<=n; i++) cout << x[i] << ‘ ‘ ;

cout << “1\n”;

else Hamiltonian (k+1);

} while (1);

void NextValue(int k)

// x[1],..., x[k-1] is a path of k-1 distinct vertices. If x[k]==0, then no vertex has as yet

// been assigned to x[k]. After execution x[k] is assigned to the next highest

// numbered vertex which i) does not already appear in x[1], x[2],..., x[k-1]; and

// ii) is connected by an edge to x[k-1]. Otherwise x[k]==0. If k==n, then

// in addition x[k] is connected to x[1].


{
do{

Dept. of AI&ML, RNSIT Page 49 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

x[k] = (x[k]+1) % (n+1); // Next vertex


if (!x[k]) return;
if (G[x[k-1]] [x[k]]) {
// Is there an edge?
for (int j=1; j<=k-1; j++)
if (x[j]==x[k])
break;
if (j==k) // Check for distinctness.
// If true, then the vertex is distinct.
If ((k<n) || ((k==n) && G[x[n]] [x[1]]))
return;
}
} while (1);
}

package javaapplication11;
import java.util.Scanner;
public class P12new {
static int [] x = new int [25];
static void Next_Vertex(int G[][],int n,int k){
int j;
while(true)
{
x[k]=(x[k]+1)%(n+1);
if(x[k]==0)
return;
if(G[x[k-1]][x[k]]!=0)
{
for(j=1;j<=k-1;j++)
{
if(x[j]==x[k])
break;
}
if(j==k)
{
if((k<n)||((k==n)&&(G[x[n]][x[1]]!=0)))
return;
}
}
}
}

static void H_Cycle(int G[][],int n,int k)


{
int i;
while(true)
{
Next_Vertex(G,n,k);
if(x[k]==0)
return;
if(k==n)

Dept. of AI&ML, RNSIT Page 50 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

{
System.out.println("\n");
for(i=1;i<=n;i++)
System.out.print(x[i] +"-->");
System.out.println(x[1]);
}
else
H_Cycle(G,n,k+1);
}
}
public static void main(String[] args) {
int i,j,n;
int [][] G = new int [25][25];
Scanner read = new Scanner(System.in);
System.out.println("Enter the number of vertices of the graph");
n=read.nextInt();
System.out.println("Enter the Path adjacency matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
G[i][j]=read.nextInt();
x[i]=0;
}
}
x[1]=1;
System.out.println(" \n Hamiltonian Cycles are");
H_Cycle(G,n,2);
}
}
OUTPUT1:
Enter the number of vertices of the graph
8
Enter the Path adjacency matrix
01100010
10100001
11010000
00101000
00010100
00001010
10000101
01000010

Hamiltonian Cycles are


1-->2-->8-->7-->6-->5-->4-->3-->1

1-->3-->4-->5-->6-->7-->8-->2-->1

OUTPUT2:
Enter the number of vertices of the graph
6
Enter the Path adjacency matrix

Dept. of AI&ML, RNSIT Page 51 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

011100
101010
110110
101011
011101
000110

Hamiltonian Cycles are


1-->2-->3-->5-->6-->4-->1

1-->2-->5-->6-->4-->3-->1

1-->3-->2-->5-->6-->4-->1

1-->3-->4-->6-->5-->2-->1

1-->4-->6-->5-->2-->3-->1

1-->4-->6-->5-->3-->2-->1

Dept. of AI&ML, RNSIT Page 52 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

DAA Laboratory viva questions


Module 1
INTRODUCTION
1. What is an algorithm?
An algorithm is a sequence of unambiguous instructions for solving a problem. i.e., for
obtaining a required output for any legitimate input in a finite amount of time.

2. State the Euclid’s algorithm for finding GCD of two given numbers.
ALGORITHM Euclid (m, n)
// Computes gcd(m,n) by Euclid’s algorithm
//Input: Two nonnegative, not-both-zero integers m and n

//Output: Greatest common divisor of m and n


while n ≠ 0 do
r mod n
m n
n r

return m.

3. What do you mean by Amortized Analysis?


Amortized analysis finds the average running time per operation over a worst case sequence
of operations. Amortized analysis differs from average-case performance in that probability is
not involved; amortized analysis guarantees the time per operation over worst-case
performance.

4. What are important problem types? (or) Enumerate some important types of
problems.
1.Sorting 2. Searching 3. Numerical problems
4. Geometric problem 5. Combinatorial Problems 6. Graph problems
7. String processing problems

5. Name some basic Efficiency classes


1. Constant 2. Logarithmic 3. Linear 4. Nlogn
5. Quadratic 6. Cubic 7. Exponential 8. factoial

6. What are algorithm design techniques?


Algorithm design techniques ( or strategies or paradigms) are general approaches to solving
problems algorithmathically, applicable to a variety of problems from different areas of
computing. General design techniques are:
(i) Brute force (ii) divide and conquer (iv) transform and conquer

(iii) decrease and conquer(v) greedy technique


(vi) dynamic programming
(vii) backtracking
(viii) branch and bound

Dept. of AI&ML, RNSIT Page 53 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

7. How is an algorithm’s time efficiency measured?


Time efficiency indicates how fast the algorithm runs. An algorithm’s time efficiency is measured as
a function of its input size by counting the number of times its basic operation (running time) is
executed. Basic operation is the most time-consuming operation in the algorithm’s innermost loop.

8. What is Big ‘Oh’ notation?


A function t(n) is said to be in O(g(n)), denoted t(n) O (g(n)) , if t(n) is bounded above by
some constant multiple of g(n) for all large n, i.e., if there exist some positive constant c and some
nonnegative integers n0 such that t(n) ≤ cg(n) for all n≥ n0

9. What is an Activation frame?


It is a storage area for an invocation of recursive program (parameters, local variables, return
address/value etc.). Activation frame allocated from frame stack pointed by frame pointer.

10. Define order of an algoriithm


Measuring the performance of an algorithm in relation with the input size n is known as order of
growth.

11. What is recursive call?


Recursive algorithm makes m ore than a single call to itself is known as recursive call. An algorithm
that calls itself is direct recursive. An algorithm”A” is said to be indirect recursive if it calls another
algorithm which in turn calls “A”.
12. What do you mean by stepwise refinement?
In top-down design methodollogy the problem is solved in sequence (step by step) is known as
stepwise refinement.

13. How is the efficiency of the algorithm defined?


The efficiency of an algorithm is defined with the components.

(i) Time efficiency -indicates how fast the algorithm runs


(ii) Space efficiency -indicates how much extra memory the algorithm needs

14. Define direct recursive and indirect recursive algorithms.


Recursion occurs where the definition of an entity refers to the entity itself. Recursion can be direct
when an entity refers to itself directly or indirect when it refers to other entities which refers to it. A
(Directly) recursive routine calls itself. Mutually recursive routines are an example of indirect
recursion. A (Directly) recursive data type contains pointers to instances of the data type.

15. What are the characteristics of an algorithm?


Every algorithm should have the following five characteristics
(i) Input (ii) Output (iii)Definiteness (iv) Effectiveness (v) Termination
Therefore, an algorithm can be defined as a sequence of definite and effective instructions, which
terminates with the production of correct output from the given input. In other words, viewed little
more formally, an algorithm is a step-by-step formalization of a mapping function to map input set
onto an output set.
Dept. of AI&ML, RNSIT Page 54 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

16. What do you mean by time complexity and space complexity of an algorithm?

Time complexity indicates how fast the algorithm runs. Space complexity deals with extra memory it
require. Time efficiency is analyzed by determining the number of repetitions of the basic operation
as a function of input size. Basic operation: the operation that contributes most towards the running
time of the algorithm The running time of an algorithm is the function defined by the number of steps
(or amount of memory) required to solve input instances of size n.

17. Define Big Omega Notation


\A function t(n) is said to be in Ω(g(n)) , denoted t(n) Є Ω((g(n)) , if t(n) is bounded below by some
positive constant multiple of g(n) for all large n, i.e., if there exist some positive constant c and some
nonnegative integer n0 such that t(n) ≥cg(n) for all for all n ≥ n0

18. What are the different criteria used to improve the effectiveness of algorithm?
(i) The effectiveness of algorithm is improved, when the design, satisfies the following constraints to
be minimum. Time efficiency - how fast an algorithm in question runs. Space efficiency – an extra
space the algorithm requires
(ii) The algorithm has to provide result for all valid inputs.

19. Analyze the time complexity of the following segment:


for(i=0;i<N;i++)

for(j=N/2;j>0;j--)

sum++;
Time Complexity= (N * N) / 2= N2 /2
Є O (N2)

20. write general plan for analyzing non-recursive algorithms.


Decide on parameter indicating an input’s size.

Identify the algorithm’s basic operation

Checking the no.of times basic operation executed depends on size of input. If it depends

on some additional property, then best, worst, avg. cases need to be investigated

Set up sum expressing the no. of times the basic operation is executed. (establishing
order of growth)

21. How will you measure input size of algorithms?

Dept. of AI&ML, RNSIT Page 55 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

The time taken by an algorithm grows with the size of the input. So the running time of the program
depends on the size of its input. The input size is measured as the number of items in the input that is
a parameter n is indicating the algorithm’s input size.

22. Define the terms: pseudocode, flow chart


A pseudocode is a mixture of a natural language and programming language like constructs.
A pseudocode is usually more precise than natural language. A flowchart is a method of
expressing an algorithm by a collection of connected geometric shapes containing descriptions of the
algorithm’s step

23. write general plan for analyzing recursive algorithms.


I. Decide on parameter indicating an input’s size.
II. Identify the algorithm’s basic operation
III. Checking the no.of times basic operation executed depends on size of input.if it depends on
some additional property, then best, worst, avg. cases need to be investigated
IV. Set up the recurrence relation, with an appropriate initial condition, for the num times the basic
operation is executed
V. Solve recurrence (establishing order of growth)

24. What do you mean by Combinatorial Problem?


Combinatorial Problems are problems that ask to find a combinatorial object-such as permutation, a
combination, or a subset--that satisfies certain constraints and has some desired property.
25. Define Big Theta Notations
A function t(n) is said to be in Θ(g(n)) , denoted t(n) Є Θ (g(n)) , if t(n) is bounded both above and
below by some positive constant multiple of g(n) for all large n, i.e., if there exist some positive
constants c1 and c2 and some nonnegative integer n0 such that c1 g(n) ≤t(n) ≤ c2g(n) for all n ≥ n0.

26. What is performance measurement?


Performance measurement is concerned with obtaining the space and the time requirements of a
particular algorithm.

27. What is an algorithm?


An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. In

addition, all algorithms must satisfy the following criteria:

1) input 2) Output 3) Definiteness 4) Finiteness 5) Effectiveness.

28. Define Program.


A program is the expression of an algorithm in a programming language. Sometimes works
such as procedure, function and subroutine are used synonymously program.

Dept. of AI&ML, RNSIT Page 56 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

29. What is recursive algorithm?


An algorithm is said to be recursive if the same algorithm is invoked in the body.

30. What is space complexity and time complexity?


The space complexity of an algorithm is the amount of memory it needs to run to completion. The
time complexity of an algorithm is the amount of computer time it needs to run to completion.

31. Give the two major phases of performance evaluation


Performance evaluation can be loosely divided into two major phases: (i) a prior estimate
(performance analysis) (ii) a Posterior testing (performance measurement)

32. Define input size.


The input size of any instance of a problem is defined to be the number of words (or the
number of elements) needed to describe that instance.

33. Define best-case step count.


The best-case step count is the minimum number of steps that can be executed for the given
parameters.

34. Define worst-case step count.


The worst-case step count is the maximum number of steps that can be executed for the given
parameters.

35. Define average step count.


The average step count is the average number of steps executed an instance with the given
parameters.

36. Define Little “oh”.


The function f(n) = 0(g(n)) iff Lim
f(n) =0 n →∞ g(n)

37. Define Little Omega.


The function f(n) = ω (g(n)) iff

Lim f(n) =0 n →∞ g(n)

38. Write algorithm using iterative function to fine sum of n numbers.


Algorithm sum(a,n)

{ S : = 0.0

For i=1 to n do S : - S
Dept. of AI&ML, RNSIT Page 57 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

+ a[i]; Return S; }

39. Write an algorithm using Recursive function to fine sum of n numbers,


Algorithm Rsum (a,n)

if(n≤0) then

Return 0.0;

Else Return Rsum(a, n- 1) + a(n);

40.What are Sequential Algorithms?

The central assumption of the RAM model is that instructions are executed one after another, one
operation at a time. Accordingly, algorithms designed to be executed on such machines are called
Sequential algorithms.

41.What are Parallel Algorithms?

The central assumption of the RAM model does not hold for some newer computers that can execute
operations concurrently, i.e., in parallel algorithms that take advantage of this capability are called
Parallel algorithms.

42.What is Exact and Approximation algorithm?


The principal decision to choose solving the problem exactly is called exact algorithm.The principal
decision to choose solving the problem approximately is called Approximation algorithm.

43.What is Algorithm Design Technique? Nov/Dec 2005

An algorithm design technique is a general approach to solving problems algorithmically that is


applicable to a variety of problems from different areas of computing.

44.Define Pseudo code.


A Pseudo code is a mixture of a natural language and programming language like constructs. A pseudo
code is usually more precise than a natural language, and its usage often yields more succinct algorithm
descriptions.

Dept. of AI&ML, RNSIT Page 58 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

45.Define Flowchart.
A method of expressing an algorithm by a collection of connected geometric shapes containing
descriptions of the algorithm’s steps.

46.Explain Algorithm’s Correctness

To prove that the algorithm yields a required result for every legitimate input in a finite amount of
time.
Example: Correctness of Euclid’s algorithm for computing the greatest common divisor stems from
correctness of the equality gcd (m, n) = gcd (n, m mod n).

47.What is generality of an algorithm?


It is a desirable characteristic of an algorithm. Generality of the problem the algorithm solves is
sometimes easier to design an algorithm for a problem posed in more general terms.

48.What is algorithm’s Optimality?


Optimality is about the complexity of the problem that algorithm solves. What is the minimum amount
of effort any algorithm will need to exert to solve the problem in question is called algorithm’s
Optimality.

49.What do you mean by “Sorting” problem?


The sorting problem asks us to rearrange the items of a given list in ascending order (or descending
order)

50.What do you mean by “Searching” problem?


The searching problem deals with finding a given value, called a search key, in a given set.

51.What do you mean by “Worst case-Efficiency” of an algorithm?

The ²Worst case-Efficiency” of an algorithm is its efficiency for the worst-case input of size n, which
is an input (or inputs) of size n for which the algorithm runs the longest among all possible inputs of
that size.
Ex: if you want to sort a list of numbers in ascending order when the numbers are given in descending
order. In this running time will be the longest.

52.What do you mean by “Best case-Efficiency” of an algorithm?

The ²Best case-Efficiency” of an algorithm is its efficiency for the Best-case input of size n, which is
an input(or inputs) of size n for which the algorithm runs the fastest among all possible inputs of that
size.

Ex: if you want to sort a list of numbers in ascending order when the numbers are given in ascending
order. In this running time will be the smallest.

Dept. of AI&ML, RNSIT Page 59 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

53.Define the “Average-case efficiency” of an algorithm?


The ²Average-case efficiency” of an algorithm is its efficiency for the input of size n, for
which the algorithm runs between the best case and the worst case among all possible inputs of that
size.

54.What do you mean by “Amortized efficiency”?

The “Amortized efficiency” applies not only a single run of an algorithm but rather to a sequence of
operations performed on the same data structure. It turns out that in some situations a single operation
can be expensive ,but the total time for an entire sequence of n such operations is always significantly
better than the worst case efficiency of that single operation multiplied by n. This is known as
“Amortized efficiency

55.How to measure the algorithm’s efficiency?

It is logical to investigate the algorithm’s efficiency as a function of some parameter n indicating the
algorithm’s input size.

Example: It will be the size of the list for problems of sorting, searching, finding the list’s smallest
element, and most other problems dealing with lists.

56.What is called the basic operation of an algorithm?


The most important operation of the algorithm is the operation contributing the most to the total
running time is called basic operation of an algorithm.

57.How to measure an algorithm’s running time?

Let Cop be the time of execution of an algorithm’s basic iteration on a particular computer
and let C (n) be the number of times this operation needs to be executed for this algorithm.

Then we can estimate the running time T(n) of a program implementing this algorithm on

that computer by the formula


T(n) ≈ Cop C(n)

58.Define order of growth.


The efficiency analysis framework concentrates on the order of growth of an algorithm’s basic
operation count as the principal indicator of the algorithm’s efficiency. To compare and rank such
orders of growth we use three notations
(Big oh) notation
Ω (Big Omega) notation &
Θ (Big Theta) notation

59.Prove that(½)n(n-1) Î Q(n2)


Dept. of AI&ML, RNSIT Page 60 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

1/2n(n-1)=(1/2)n2-1/2n £ 1/2 n2 for all n³0.(we have proved upper inequality) now 1/2n(n-1)=(1/2)n2 -
1/2n³(1/2)n2-1/2n*1/2n(for all n³2)=1/4 n2 hence we can select c2=1/4,c1=1/2 and n0=2.

60.What is the use of Asymptotic Notations?

The notations O, W and Q and are used to indicate and compare the asymptotic orders of growth of
functions expressing algorithm efficiencies

MODULE 2
DIVIDE AND CONQUER

1. Define the divide and conquer method.


Given a function to compute on ‘n’ inputs the divide-and-comquer strategy suggests splitting the
inputs in to’k’ distinct susbsets, 1<k <n, yielding ‘k’ subproblems. The subproblems must be solved,
and then a method must be found to combine subsolutions into a solution of the whole. If the
subproblems are still relatively large, then the divide-and conquer strategy can possibly be reapplied.

2. Define control abstraction.


A control abstraction we mean a procedure whose flow of control is clear but whose primary operations
are by other procedures whose precise meanings are left undefined.
Write the Control abstraction for Divide-and conquer.
Algorithm DAndC(P)
{
if small(p) then return S(P);
else
{
divide P into smaller instance p1,p2,…pk, k ≥1; Apply DAndC to each of these subproblems Return
combine (DAnd C(p1) DAnd C(p2),----, DAnd (pk)); }
}

3.What is the substitution method?


One of the methods for solving any such recurrence relation is called the substitution method.

4. What is the binary search?


If ‘q’ is always chosen such that ‘q’ is the middle element(that is, q=[(n+1)/2], then the resulting
search algorithm is known as binary search.

5. Give computing time for Binary search?


In conclusion we are now able completely describe the computing time of binary search by giving
formulas that describe the best, average and worst cases. Successful searches
Θ(1) Θ (logn) Θ (Logn)

best average worst

Unsuccessful searches
Dept. of AI&ML, RNSIT Page 61 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

Θ (logn)

best, average, worst

6. Define external path length?


The external path length E, is defines analogously as sum of the distance of all external nodes from the
root.

7. Define internal path length.


The internal path length ‘I’ is the sum of the distances of all internal nodes from the root.

8. What is the maximum and minimum problem?


The problem is to find the maximum and minimum items in a set of ‘n’ elements. Though this problem
may look so simple as to be contrived, it allows us to demonstrate divideand-conquer in simple setting.

9. What is the Quick sort?


Quicksort is divide and conquer strategy that works by partitioning it’s input elements according to
their value relative to some preselected element(pivot). it uses recursion and the method is also called
partition –exchange sort.

10. Write the Analysis for the Quick sort.


O(nlogn) in average and best cases O(n2) in worst case

11. what is Merge sort? and Is insertion sort better than the merge sort?
Merge sort is divide and conquer strategy that works by dividing an input array in to two halves,sorting
them recursively and then merging the two sorted halves to get the original array sorted Insertion sort
works exceedingly fast on arrays of less then 16 elements, though for large‘n’ its computing time is
O(n2).

12. Write a algorithm for straightforward maximum and minimum?


Algorithm straight MaxMin(a,n,max,min)
//set max to the maximum and min to the minimum of a[1:n]
{
max := min: = a[i];
for i = 2 to n do
{
if(a[i] >max) then max: = a[i];
if(a[i] >min) then min: = a[i];
} }

13. what is general divide and conquer recurrence?

Dept. of AI&ML, RNSIT Page 62 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

Time efficiency T(n)of many divide and conquer algorithms satisfies the equation
T(n)=a.T(n/b)+f(n).This is the general recurrence relation.

14. What is Master’s theorem?

15. Write the algorithm for Iterative binary search?


Algorithm BinSearch(a,n,x)
//Given an array a[1:n] of elements in nondecreasing
// order, n>0, determine whether x is present
{
low : = 1;
high : = n;
while (low < high) do
{
mid : = [(low+high)/2];
if(x < a[mid]) then high:= mid-1; else if (x
>a[mid]) then low:=mid + 1; else return mid;
} } return 0;

16. Describe the recurrence relation for merge sort?


If the time for the merging operation is proportional to n, then the computing time of

merge sort is described by the recurrence relation


T(n) = a n = 1, a a constant
2T (n/2) + n n >1, ca

17. What can we say about the average case efficiency of binary search?
A sophisticated analysis shows that the average number of key comparisons made by binary search is
only slightly smaller than that in the worst case Cavg(n) log2n

18.Define Binary Tree


A binary tree T is defined as a finite set of nodes that is either empty or consists of s root and two
disjoint binary trees TL, and TR called, respectively the left and right subtree of the root.

19.How divide and conquer technique can be applied to binary trees?


Since the binary tree definition itself divides a binary tree into two smaller structures of the same type,
the left subtree and the right subtree, many problems about binary trees can be solved by applying the
divide-conquer technique.

20. Explain Internal and External Nodes


To draw the tree's extension by replacing the empty subtrees by special nodes.The extra
nodes shown by little squares are called external. The original nodes shown by littile circles
Dept. of AI&ML, RNSIT Page 63 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

are called internal.

21. Define Preorder, inorder and postorder Traversal


PREORDER -The root is visited before the left and right subtrees are visited (in that order)
INORDER -The root is visited after visiting its left subtree but before visiting the right subtree

POSTORDER - The root is visited after visiting the left and right subtrees(in that order)

22..Explain divide and conquer method.

23.Explain Binary search algorithm with an example by constructing recursive call


tree. Justify how it uses divide and conquer method.

24.Explain Merge sort algorithm with an example by constructing recursive call tree.justify
how it uses divide and conquer method.

25.Explain Quick sort algorithm with an example by constructing recursive call tree.justify
how it uses divide and conquer method.

26. Differentiate Merge sort and quick sort.


27. what is the best, worst and average cases in merge sort?
28.what is the best,worst and average cases in quick sort?

29.Expalin with an example how stragens’s matrix multiplication uses divide and conquer
approach. Write its time complexity.

30.list the problems that can be solved using divide and conquer method.

31.Explain how conquering happens in the quick sort.

32.Explain Decrease and conquer method with its variations.

33.Explain Topoloical sort using both OFS and source removal method with an example.
justify how it uses decrease and conquer approach.

34.Differentiate divide and conquer,decrease and conquer.

35.List the problems that can be solved using decrease and conquer method.

Dept. of AI&ML, RNSIT Page 64 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

MODULE 3
GREEDY METHOD

1. Explain the greedy method.


Greedy method is the most important design technique, which makes a choice that looks best at that
moment. A given ‘n’ inputs are required us to obtain a subset that satisfies some constraints that is the
feasible solution. A greedy method suggests that one can device an algorithm that works in stages
considering one input at a time.

2. Define feasible and optimal solution.


Given n inputs and we are required to form a subset such that it satisfies some given constraints then
such a subset is called feasible solution. A feasible solution either maximizes or minimizes the given
objective function is called as optimal solution.

3. Write the control abstraction for greedy method.


Algorithm Greedy (a, n)
{
solution=0;
for i=1 to n do
{
x= select(a);
if feasible(solution ,x) then solution=Union(solution ,x);
}
return solution;
}

5. What is a minimum cost spanning tree?


A spanning tree of a connected graph is its connected acyclic subgraph that contains all vertices of a
graph. A minimum spanning tree of a weighted connected graph is its spanning tree of the smallest
weight where bweight of the tree is the sum of weights on all its
edges. A minimum spanning subtree of a weighted graph (G,w) is a spanning subtree of G of minimum
weight w(T )= Σ w(e ) e€ T Minimum Spanning Subtree Problem: Given a weighted connected
undirected graph (G,w), find a minimum spanning subtree
6. Specify the algorithms used for constructing Minimum cost spanning tree.
a) Prim’s Algorithmb) Kruskal’s Algorithm

7. State single source shortest path algorithm (Dijkstra’s algorithm).


For a given vertex called the source in a weigted connected graph,find shotrtest paths to all its other
vertices.Dijikstra’s algorithm applies to graph with non-negative weights only.

8. What is Knapsack problem?


A bag or sack is given capacity and n objects are given. Each object has weight wi and profit pi
.Fraction of object is considered as xi (i.e) 0<=xi<=1 .If fraction is 1 then entire object is put into
sack. When we place this fraction into the sack we get wixi and pixi.
Dept. of AI&ML, RNSIT Page 65 2021-22
21CS42: Design and Analysis of Algorithms Laboratory

9. Write any two characteristics of Greedy Algorithm?


To solve a problem in an optimal way construct the solution from given set of candidates. As the
algorithm proceeds, two other sets get accumulated among this one set contains the candidates
that have been already considered and chosen while the other set contains the candidates that
have been considered but rejected.

10. What is the Greedy approach?


The method suggests constructing solution through sequence of steps,each expanding partially
constructed solution obtained so far,until a complete solution is reached. On each step,the choice must
be

Feasible(satisfy problem constraints)

Locally optimal(best local choice among all feasible choices available on that step)

Irrevocable(once made,it cant be changed)

11. What are the steps required to develop a greedy algorithm?


1.Determine the optimal substructure of the problem.
2.Develop a recursive solution.
3.Prove that at any stage of recursion one of the optimal choices is greedy choice. Thus it is always
safe to make greedy choice.
4.Show that all but one of the sub problems induced by having made the greedy choice are empty.
5.Develop a recursive algorithm and convert into iterative algorithm.

12. Define forest.


Collection of sub trees that are obtained when root node is eliminated is known as forest

13. Write the difference between the Greedy method and Dynamic programming.

14.state the requirement in optimal storage problem in tapes.

Finding a permutation for the n programs so that when they are stored on the tape in this order the
MRT is minimized.This problem fits the ordering paradigm.

15. state efficiency of prim’s algorithm.

16. State Kruskal Algorithm.


The algorithm looks at a MST for a weighted connected graph as an acyclic subgraph with |v|-1
edges for which the sum of edge weights is the smallest.

Dept. of AI&ML, RNSIT Page 66 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

17. state efficiency of Dijkstra’s algorithm.

18. Differentiate subset paradigm and ordering paradigm

19. Define Spanning Tree


A Spanning Tree of a connected graph is its connected acyclic subgraph(i.e., a tree) that contains all
the vertices of the graph.

20. Define Minimum Spanning Tree


A minimum spanning tree of a weighted connected graph is its spanning tree of the smallest weight
,where the weight of a tree is defined as the sum of the weights on all its edges.

21. Define min-heap


A min-heap is a complete binary tree in which every element is less than or equal to its children. All
the principal properties of heaps remain valid for min-heaps, with some obvious modifications.

22. Define Kruskal's Algorithm


Kruskal's algorithm looks at a minimum spanning tree for a weighted connected graph G =(V,E) as an
acyclic subgraph with | V| - 1 edges for which the sum of the edge weights is the smallest.

23. Define Prim's Algorithm


Prim's algorithm is a greedy algorithm for constructing a minimum spanning tree of a
weighted connected graph.It works by attaching to a previously constructed subtree a vertex
to the vertices already in the tree.

24. Explain Dijkstra's Algorithm


Dijkstra's algorithm solves the single - source shortest - path problem of finding shortest paths from a
given vertex (the source) to all the other vertices of a weighted graph or digraph. It works as prim's
algorithm but compares path lengths rather than edge lengths. Dijkstra's algorithm always yields a
correct solution for a graph with nonnegative weights.

25.Explain Greedy method.

26.List the different problems that can be solved using greedy method.

27.What is feasible solution?

28.what is optimal solution?

29.What is coin change problem?

Dept. of AI&ML, RNSIT Page 67 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

30.What are different types of knapsack problems,explain with an example.justify how the knapsack
problem uses greedy method.

31.Expain job requencing with deadlines with an example.justify how it uses greedy method.

32.What is spanning tree?Explian with an example.

33.What is minimum cost Spanning tree? Explian with an example.

34.Explain prims algorithm with an example .justify how it uses greedy method.write its complexity.

35.Explain Kruskal’s algorithm with an example .justify how it uses greedy method.write its
complexity.

36.what are the proceduaral difference between prims and kruskal’s algorithm.

37.Explain single source shortest path problem using dijkstras algorithm with an example.justify how
it uses greedy method.

38.How single source shortest path problem can be converted in to all pairs shortest path
problem.justify with an example.

39.Give real time example of prime and krurkals algorithm.

40.What is Huffman trees and codes.

41.Explain transform and conquer method.

42. Define Heap,Min heap,Max heap.

43.Show the construction of max/min heap with an example.

44.Once the max/min heap constructed show how the inserution or deletion will taker place.

explain with an example.

45.Explain the Heap sort with an example .justify how it uses transform and conquer approach.

Dept. of AI&ML, RNSIT Page 68 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

MODULE 4
DYNAMIC PROGRAMMING

1. Write the difference between the Greedy method and Dynamic programming.

2. Define dynamic programming.


Dynamic programming is an algorithm design method that can be used when a solution to the problem
is viewed as the result of sequence of decisions. It is technique for solving problems with overlapping
subproblems.

3. What are the features of dynamic programming?


Optimal solutions to sub problems are retained so as to avoid recomputing of their values.
Decision sequences containing subsequences that are sub optimal are not considered.
It definitely gives the optimal solution always.

4. What are the drawbacks of dynamic programming?


Time and space requirements are high, since storage is needed for all level.
Optimality should be checked at all levels.

5. Write the general procedure of dynamic programming.


The development of dynamic programming algorithm can be broken into a sequence of 4 steps.
1. Characterize the structure of an optimal solution.
2. Recursively define the value of the optimal solution.
3. Compute the value of an optimal solution in the bottom-up fashion.
4. Construct an optimal solution from the computed information.
[[
6. Define principle of optimality.
It states that an optimal solution to any of its instances must be made up of optimal solutions to its
subinstances.

7. Define multistage graph


A multistage graph G =(V,E) is a directed graph in which the vertices are partitioned in to K>=2 disjoint
sets Vi,1<=i<=k.The multi stage graph problem is to find a minimum cost paths from s(source ) to
t(sink)Two approach(forward and backward)

8. Define All pair shortest path problem


Given a weighted connected graph, all pair shortest path problem asks to find the lengths of shortest
paths from each vertex to all other vertices.

9.Define Distance matrix


Recording the lengths of shortest path in n x n matrix is called Distance matrix(D)

Dept. of AI&ML, RNSIT Page 69 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

10.Define floyd’s algorithm


To find all pair shortest path.The algorithm computes the distance matrix of a weighted graph with n
vertices through series of n by n matrices :D(0)…D(k-1),D(k)…..D(n)

11. State the time efficiency of floyd’s algorithm

12. Define OBST

Dynammic pgmg. Used. If probabilities of searching for elements of a set are known then finding
optimal BST for which the average number of comparisons in a search is smallest possible.

13. Define Catalan number


The total number of binary search trees with n keys is equal to nth Catalan number
C(n)=(2n to n) 1/(n+1) for n>0,c(0)=1

14. Define Transitive closure


The transitive closure of a directed graph with n vertices can be defined as the n by n Boolean matrix
T = {ti,}, in which the element in the ith row (1<i<n) and the j th column (l<j<n) is 1 if there exists a
non trivial directed path from the ith vertex to jth vertex ; otherwise , tij is 0.

.
15. Explain Warshalls algorithm
Warshall's algorithm constructs the transitive closure of a given digraph with n vertices through a series
of n by n Boolean matrices R(0), ………, R(k-l)R(k),…….., R(n)
Each of these matrices provides certain information about directed paths in the digraph.

16. What does Floyd’s algorithm do?


It is used to find the distances (the lengths of the shortest paths) from each vertex to all other vertices
of a weighted connected graph.

17. Explain principle of Optimality


It says that an optimal solution to any instance of an optimization problem is composed of optimal
solutions to its subinstances.

18. Explain Knapsack problem


Given n items of known weights w1,w2...........wn and values v1,v2............vn and a knapsack
of capacity W, find the most valuable subset of the items that fit into the knapsack.(Assuming all the
weights and the knapsack's capacity are positive integers the item values do not have to be integers.)

19.Explain the Memory Function technique


The Memory Function technique seeks to combine strengths of the top down and bottom-up
approaches to solving problems with overlapping subproblems. It does this by solving, in the top-down

Dept. of AI&ML, RNSIT Page 70 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

fashion but only once, just necessary sub problems of a given problem and recording their solutions in
a table.

20. Explain Traveling salesman problem”?


A salesman has to travel n cities starting from any one of the cities and visit the remaining cities exactly
once and come back to the city where he started his journey in such a manner that either the distance
is minimum or cost is minimum. This is known as traveling salesman problem.

21.Explain Dynamic programming.

22.List the problems which can be solved using dynamic programming method.

23.Explain multistage graph with an example.

24.What is transitive closure of a graph? Explain with example.

25.What is adjacency matrix?

26.What are the different types of adjacency matrix?

27.Explain warshall’s algorithm with an example.Justify how it uses dynamic programming method.

28.Explain Floud’s Algorithm with an example.Justify how it uses dynamic programming method.

29.What is the outcome of warshall’s algorithm?

30.What is the outcome of floyd’s algorith

31.What is optimal binary search tree? How it can be differentiate with binary search tree justify with
an example.

32.How knoaprack can be solved using dynamic programming?explain withan example.

33.suggest different methods which can be solved knaprack problem using dynamic programming?

34.What is the advantage of Bellman ford algorithm with dijkrtra’s algorithm.

35.Explain travelling salesperson problem with an example.justify how it user dynamic programming
method.

36.Explain Reliability design.

Dept. of AI&ML, RNSIT Page 71 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

MODULE 5
BACKTRACKING

1.what are the requirements that are needed for performing Backtracking?
To solve any problem using backtracking, it requires that all the solutions satisfy a complex set of
constraints. They are: i. Explicit constraints. ii. Implicit constraints.
i
2.Define state space tree.
The tree organization of the solution space is referred to as state space tree.

3.Define state space of the problem.


All the paths from the root of the organization tree to all the nodes is called as state space of the
problem

4.Define answer states.


Answer states are those solution states s for which the path from the root to s defines a tuple that is a
member of the set of solutions of the problem.

5.What are static trees?


The tree organizations that are independent of the problem instance being solved are called as static
tree.

6.What are dynamic trees?


The tree organizations those are independent of the problem instance being solved are called as static
tree.

7.Define a live node.


A node which has been generated and all of whose children have not yet been generated is called as
a live node

8. Define a E – node.
E – node (or) node being expanded. Any live node whose children are currently being generated is
called as a E – node.

9.Define a dead node.


Dead node is defined as a generated node, which is to be expanded further all of whose children
have been generated.

10.Define Branch-and-Bound method.


The term Branch-and-Bound refers to all the state space methods in which all children of the E-node
are generated before any other live node can become the E- node.

11.What are the searching techniques that are commonly used in Branch-and-Bound method

Dept. of AI&ML, RNSIT Page 72 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

The searching techniques that are commonly used in Branch-and-Bound method. I FIFO ii.
LIFO iii. LC iv. Heuristic search

12.State 8 – Queens problem.


The problem is to place eight queens on a 8 x 8 chessboard so that no two queen “attack” that is,
so that no two of them are on the same row, column or on the diagonal.

13.State Sum of Subsets problem.


Given n distinct positive numbers usually called as weights , the problem calls for finding all the
combinations of these numbers whose sums are m.

14. State m – colorability decision problem.


Let G be a graph and m be a given positive integer. We want to discover whether the nodes of G can
be colored in such a way that no two adjacent nodes have the same color yet only m colors are used.

15.Define chromatic number of the graph.


The m – colorability optimization problem asks for the smallest integer m for which the graph G can
be colored. This integer is referred to as the chromatic number of the graph.

16. Define a planar graph.


A graph is said to be planar iff it can be drawn in such a way that no two edges cross each other.

17. What are NP- hard and Np-complete problems?


The problems whose solutions have computing times are bounded by polynomials of small degree.

18. What is a decision problem?


Any problem for which the answer is either zero or one is called decision problem.

19. what is approximate solution?


A feasible solution with value close to the value of an optimal solution is called approximate solution.

20. what is promising and non-promising nodes?


a node in a state space tree is said to be promising if it corresponds to a partially constructed solution
from which a complete solution can be obtained.
The nodes which are not promising for solution in a state space tree are called non-promising nodes.

21.Write formula for bounding function in Knapsack problem

In knapsack problem upper bound value is computed by the formula


UB = v + (W-w) * (vi+1/wi+1)

22. Write about traveling salesperson problem.

Dept. of AI&ML, RNSIT Page 73 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

Let g = (V, E) be a directed. The tour of G is a directed simple cycle that includes every vertex in V.
The cost of a tour is the sum of the cost of the edges on the tour. The traveling salesperson problem is
to find a tour of minimum cost.In branch and bound technique of TSP problem Lower bound lb= s/2

23. Write some applications of traveling salesperson problem.


Routing a postal van to pick up mail from boxes located at n different sites.
Using a robot arm to tighten the nuts on some piece of machinery on an assembly line.
Production environment in which several commodities are manufactured on the same set of
machines.

24. Give the time complexity and space complexity of traveling salesperson problem.

25. Differentiate decision problem and optimization problem


Any problem for which the answer is either zero or one is called decision problem.Any problem that
involves the identification of an optimal (maximum or minimum) value of a given cost function is
called optimization problems

26. what is class P and NP?


P is set of all decision problems solvable by deterministic algorithms in polynomial time. NP is set
of all decision problems solvable by non deterministic algorithms in polynomial time.
27. Define NP-Hard and NP-Complete problems
Problem L is NP-Hard if and only if satisfiability reduces to L.
A Problem L is NP-Complete if and only if L is NP-Hard and L belongs to NP.

28. Explain promising and nonpromising node


A node in a state space tree is said to be promising if it corresponds to a partially

constructed solution that may still lead to lead to a complete solution; otherwise it is called
nonpromising.

29. Explain n-Queens problem


The problem is to place n queens on an n by n chessboard so that no two queens attack each other by
being in the same row or same column or on the same diagonal.

30. Explain Subset-Sum Problem


We consider the subset-sum problem: Find a subset of a given set S={S1,S2,..........Sn} of n positive
integers whose sum is equal to a given positive integer d.

31. Explain Branch and Bound Technique


Compared to backtracking, branch and bound requires .The idea to be strengthened further if we deal
with an optimization problem, one that seeks to minimize or maximize an objective function, usually
subject to some constraints.

Dept. of AI&ML, RNSIT Page 74 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

32.Define Feasible Solution


A feasible solution is a point in the problem's search space that satisfies all the problem's constraints.Ex:
A Hamiltonian Circuit in the traveling salesman problem. A subset of items whose total weight does
not exceed the knapsack's Capacity

33. Define Optimal solution


Is a feasible solution with the best value of the objective function
Eg: The shortest Hamiltonian Circuit m, The most valuable subset of items that fit the knapsack

34.Mention two reasons to terminate a search path at the current node in a state-space tree of a
branch and bound algorithm.
The value of the node's bound is not better than the value of the best solution seen so far. The node
represents no feasible solutions because the constraints of the problem are already violated.

35. Explain “Graph coloring” problem.


The graph coloring problem asks us to assign the smallest number of colors to vertices of a graph so
that no two adjacent vertices are the same color.

36.Explain Knapsack Problem

Find the most valuable subset of n items of given positive integer weights and values that fit into a
knapsack of a given positive integer capacity.

37. Define tractable and intractable problems


Problems that can be solved in polynomial time are called tractable problems, problems that cannot be
solved in polynomial time are called intractable problems.

38. Explain the theory of computational complexity


A problem's intractability remains the same for all principal models of computations and all reasonable
input encoding schemes for the problem under consideration

39.Explain class P problems


Class P is a class of decision problems that can be solved in polynomial time by(deterministic)
algorithms. This class of problems is called polynomial.

40.Explain undecidable problems


If the decision problem cannot be solved in polynomial time, and if the decision problems cannot be
solved at all by any algorithm. Such problems are called Undecidable.
41. Explain the halting problem
Given a computer program and an input to it,determine whether the program will halt on that input or
continue working indefinitely on it.

Dept. of AI&ML, RNSIT Page 75 2021-22


21CS42: Design and Analysis of Algorithms Laboratory

42. Explain class NP problems


Class NP is the class of decision problems that can be solved by nondeterministic polynomial
algorithms.Most decision problems are in NP. First of all, this class includes all the problems in P. This
class of problems is called Nondeterministic polynomial.

43.Explain NP-complete problems


A decision problem d is said to be NP-complete if
1) it belongs to class NP 2)every problem in NP is polynomially reducible to D.

44.When a decision problem is said to be polynomially reducible

45. Define a Heuristic


A heuristic is a common-sense rule drawn from experience rather than from a mathematically proved
assertion. Ex: Going to the nearest unvisited city in the traveling salesman problem is a good illustration
for Heuristic

46. Explain NP-Hard problems


The notion of an NP-hard problem can be defined more formally by extending the notion of
polynomial reducability to problems that are not necessary in class NP including optimization
problems.

47.Define Traversals.
When the search necessarilyinvolves the examination of every vertex in the object being searched
it is called a traversal.

48.List out the techniques for traversals in graph.


i) Breadth first search ii) Depth first search

49.What is articulation point.


A vertex v in a connected graph G is an articulation point if and only if the deletion of vertex
v together with all edged incident to v disconnects the graph in to two or more nonempty
components.

50. Explain Backtracking.


51. List the problems that can be solved using backtracking method.
52. Explain N-queens problem, write state space tree for 4_queens’ problem and justify How it uses
backtracking method.
53. Explain sum subset problem, write state space tree and justify how it uses backtracking method.
54.Explain Graph closing, write state space tree and justify how it uses backtracking method.
55. Explain Hamiltonian cycle problem, write state space tree and justify how it uses backtracking
method.
56. Explain branch and bound.
57. List the different problems that can be solved using branch and bound method.
58.Differentiate Branch & bound, Backtracking.
Dept. of AI&ML, RNSIT Page 76 2021-22

You might also like