SlideShare a Scribd company logo
1 of 75
Download to read offline
JAWAHARLAL NEHRU NATIONAL COLLEGE
OF ENGINEERING
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
A Laboratory Manual
On
DESIGN AND ANALYSISOF
ALGORITHMS LABoRATORY
(18CSL47)
Prepared By
Dr. RAVINDRA S. Mr. NARENDRA KUMAR S
Associate Professor Assistant Professor
Dept. of CSE Dept. of CSE
Vision
To be one of the pre-eminent departments to provide technical and knowledge based
education, utilizing the potential of Computer Science & Engineering to meet the ever
changing needs of industry and society.
Mission
M1: Mould the students to meet the emerging challenges of industry and society.
M2: Emphasizing on research
M3 Effective industry interaction for the development of state of the art technological
infrastructure and faculty component.
JAWAHARLAL NEHRU NATIONAL COLLEGE OF ENGINEERING
Department of Computer Science and Engineering
Program Educational Objectives
Graduates of the Program:
PEO -1 Would be able to identify real world problems and solve them effectively
using comprehensive knowledge of computer science.
PEO -2 Would be able to become entrepreneur, pursue higher education and carry out
research.
PEO -3 To work in changing environment with ethical and social responsibilities.
Program Specific Outcomes
PSO -1
Apply concepts in the core areas of Computer Science & Engineering –
Networking, Data Structures, Computer Architecture, Mathematical
Modeling and System Programming to address technical issues.
PSO -2
Design and develop computer based systems by applying standard
practices and principles using appropriate tools and programming
languages for real world problems.
Program Outcomes
PO 1 Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of
complex engineering problems.
PO 2 Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering
sciences.
PO 3 Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations.
PO 4 Use research-based knowledge and research methods including
design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
PO 5 Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling
to complex engineering activities with an understanding of the
limitations.
PO 6 Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO 7 Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
PO 8 Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO 9 Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO 10 Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able
to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive
clear instructions.
PO 11 Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in
multidisciplinary environments.
PO 12 Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context
of technological change.
Syllabus
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY
Sub. Code: 17CSL47 IA Marks 40
Number of Lecture Hours/Week: 01 I + 02 P Exam Hours 03
Total Hours: 40 Exam Marks : 60
CREDITS 02
Design, develop, and implement the specified algorithms for the following problems using
Java language under LINUX /Windows environment. Netbeans/Eclipse IDE tool can be used
for development and demonstration.
1. A. Create a Java class called Student with the following details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create nStudent objects and print the USN, Name, Branch, and
Phoneof these objects with suitable headings.
B. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.
2. A. Design a superclass called Staff with details as StaffId, Name, Phone, Salary.
Extend this class by writing three subclasses namely Teaching (domain, publications),
Technical (skills), and Contract (period). Write a Java program to read and display at least 3
staff objects of all three categories.
B. Write a Java class called Customer to store their name and date_of_birth. The
date_of_birth format should be dd/mm/yyyy. Write methods to read customer data as <name,
dd/mm/yyyy> and display as <name, dd, mm, yyyy> using StringTokenizer class considering
the delimiter character as “/”.
3. A. Write a Java program to read two integers a and b. Compute a/b and print, when b
is not zero. Raise an exception when b is equal to zero.
B. Write a Java program that implements a multi-thread application that has three threads.
First thread generates a random integer for every 1 second; second thread computes the
square of the number and prints; third thread will print the value of cube of thenumber.
4. Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to sort.
Plot a graph of the time taken versus 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.
5. Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program for varied values of n> 5000, and record the time taken to sort.
Plot a graph of the time taken versus 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.
6. Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming
method (b) Greedy method.
7. From a given vertex in a weighted connected graph, find shortest paths to other
vertices using Dijkstra's algorithm. Write the program in Java.
8. Find Minimum Cost Spanning Tree of a given connected undirected graph using
Kruskal's algorithm. Use Union-Find algorithms in your program.
9. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s
algorithm.
10. Write Java programs to (a) Implement All-Pairs Shortest Paths problem using Floyd's
algorithm.
(b) Implement Travelling Sales Person problem using Dynamic programming.
11. Design and implement in Java to find a subset of a given set S = {Sl, S2, ,Sn} of n
positive integers whose SUM is equal to a given positive integer d. For example, if S ={1, 2,
5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the
given problem instance doesn't have a solution.
12. Design and implement in Java to find all Hamiltonian Cycles in a connected
undirected Graph G of n vertices using backtracking principle.
Design and Analysis of AlgorithmsLaboratory (17CSL47)
Department of CSE, JNNCE, Shimoga Page 1
1A.Create a Java class called Student with the following details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create n Student objects and print the USN, Name, Branch, and Phone
of these objects with suitable headings.
importjava.util.*;
public class student
{
String usn;
String name;
String branch;
long phone;
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of Students:");
int n = scan.nextInt();
students[]=new student[n];
for(inti=0;i<n;i++)
s[i]=new student();
for(inti=0;i<n;i++)
{
System.out.print("Enter usn:");
s[i].usn = scan.next();
System.out.print("Enter name:");
s[i].name = scan.next();
System.out.print("Enter branch:");
s[i].branch = scan.next();
System.out.print("Enter phone number:");
s[i].phone = scan.nextLong();
}
System.out.println("USN" + "tNAME" + "tBRANCH" + "tPHONE");
for(inti=0;i<n;i++)
{
System.out.println(s[i].usn + "t" + s[i].name + "t" + s[i].branch + "t" + s[i].phone);
Design and Analysis of AlgorithmsLaboratory (15CSL47)
}
}
Department of CSE, JNNCE, Shimoga Page 2
}
Output:
Enter number of Students:3
Enter usn:4JN18CS001
Enter name:Levitin
Enter branch:CSE
Enter phone number:9988776655
Enter usn:4JN18EC002
Enter name:Sahni
Enter branch:ECE
Enter phone number:7788994455
Enter usn:4JN18IS004
Enter name:Rama
Enter branch:ISE
Enter phone number:8899552233
USN NAME BRANCH PHONE
4JN18CS001 Levitin CSE 9988776655
4JN18EC002 Sahni ECE 7788994455
4JN18IS004 Rama ISE 8899552233
Department of CSE, JNNCE, Shimoga Page 3
Design and Analysis of AlgorithmsLaboratory (15CSL47)
1B. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display()
methods to demonstrate its working.
importjava.util.*;
classstack
{
staticintst[];
staticint top = -1;
staticintsz;
static void push()
{
Scanner s = new Scanner(System.in);
System.out.print("Enter element to push : ");
int n = s.nextInt();
if(top+1 >= sz)
{
}
else
{
}
}
System.out.println("Overflow");
st[++top] = n;
static void pop()
{
if(top<0)
{
}
else
{
}
}
System.out.println("Underflow");
int p = st[top];
top = top-1;
System.out.println("Element poped : " + p);
static void display()
{
System.out.println("Stack elements are:");
for(inti = top; i>= 0; i--)
{
System.out.println(st[i]);
Department of CSE, JNNCE, Shimoga Page 4
Design and Analysis of AlgorithmsLaboratory (15CSL47)
}
}
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the size of the stack : ");
sz=s.nextInt();
st=new int[sz];
while(true)
{
System.out.println("1:push 2:pop 3:display");
int c=s.nextInt();
switch(c)
{
case 1: push();
break;
case 2: pop();
break;
case 3:display();
break;
default:
System.out.println("invalid");
System.exit(0);
}
}
}
}
Output:
Enter the size of the stack : 4
1:push 2:pop 3:display
2
Underflow
1:push 2:pop 3:display
1
Enter element to push : 5
1:push 2:pop 3:display
1
Enter element to push : 10
1:push 2:pop 3:display
1
Enter element to push : 20
Department of CSE, JNNCE, Shimoga Page 5
Design and Analysis of AlgorithmsLaboratory (15CSL47)
1:push 2:pop 3:display
1
Enter element to push : 25
1:push 2:pop 3:display
1
Enter element to push : 30
Overflow
1:push 2:pop 3:display
3
Stack elements are:
25
20
10
5
1:push 2:pop 3:display
2
Element poped : 25
1:push 2:pop 3:display
3
Stack elements are:
20
10
5
1:push 2:pop 3:display
Department of CSE, JNNCE, Shimoga Page 6
Design and Analysis of AlgorithmsLaboratory (15CSL47)
2A. Design a superclass called Staff with details as StaffId, Name, Phone, Salary. Extend this class
by writing three subclasses namely Teaching (domain, publications), Technical (skills), and
Contract (period). Write a Java program to read and display at least 3 staff objects of all three
categories.
//file name should be staffmain
importjava.util.*;
class staff
{
String staffid;
String name;
long phone;
double salary;
static Scanner s;
voidread_staff()
{
Scanner s = new Scanner(System.in);
System.out.print("Enter Staffid: ");
staffid = s.next();
System.out.print("Enter Name: ");
name = s.next();
System.out.print("Enter Phone: ");
phone = s.nextLong();
System.out.print("Enter Salary: ");
salary = s.nextDouble();
}
}
class Teaching extends staff
{
String domain;
int pub;
voidread_teaching()
{
Scanner s = new Scanner(System.in);
System.out.print("Enter Domain: ");
Department of CSE, JNNCE, Shimoga Page 7
Design and Analysis of AlgorithmsLaboratory (15CSL47)
domain=s.next();
System.out.print("Enter Publication: ");
pub=s.nextInt();
}
void display()
{
System.out.println(staffid +"t"+ name +"t"+ phone +"t"+ salary +"t"+ domain +"t"+
pub);
}
}
class Technical extends staff
{
String skills;
voidread_technical()
{
Scanner s = new Scanner(System.in);
System.out.print("Enter Skills: ");
skills=s.next();
}
void display()
{
System.out.println(staffid +"t"+ name +"t"+ phone +"t"+ salary +"t"+ skills);
}
}
class Contract extends staff
{
int period;
voidread_contract()
{
Scanner s = new Scanner(System.in);
System.out.print("Enter Period: ");
period=s.nextInt();
}
void display()
{
System.out.println(staffid +"t"+ name +"t"+ phone +"t"+ salary +"t"+ period);
}
Department of CSE, JNNCE, Shimoga Page 8
Design and Analysis of AlgorithmsLaboratory (15CSL47)
}
classstaffmain
{
public static void main(String ss[])
{
Teaching t1 = new Teaching();
Technical t2 = new Technical();
Contract t3 = new Contract();
t1.read_staff();
t1.read_teaching();
t2.read_staff();
t2.read_technical();
t3.read_staff();
t3.read_contract();
System.out.println("Staffid Name phone salary Domain publication");
t1.display();
System.out.println("Staffid Name phone salary Skills");
t2.display();
System.out.println("Staffid Name phone salary Contract");
t3.display();
}
}
Output:
Enter Staffid: 1
Enter Name: Levitin
Enter Phone: 9988776655
Enter Salary: 10000
Enter Domain: CSE
Enter Publication: 12
Enter Staffid: 2
Enter Name: Sahni
Enter Phone: 8877996655
Enter Salary: 15000
Enter Skills: writing
Enter Staffid: 3
Enter Name: Rama
Department of CSE, JNNCE, Shimoga Page 9
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Enter Phone: 7788994455
Enter Salary: 20000
Enter Period: 2
Staffid Name phone salary Domain publication
1 Levitin 9988776655 10000.0 CSE 12
Staffid Name phone salary Skills
2 Sahni 8877996655 15000.0 writing
Staffid
3
Name
Rama
phone
7788994455
salary
20000.0
Contract
2
Department of CSE, JNNCE, Shimoga Page 10
Design and Analysis of AlgorithmsLaboratory (15CSL47)
2B. Write a Java class called Customer to store their name and date_of_birth. The date_of_birth
format should be dd/mm/yyyy. Write methods to read customer data as <name, dd/mm/yyyy> and
display as <name, dd, mm, yyyy> using StringTokenizer class considering the delimiter character
as “/”.
importjava.util.*;
public class customer
{
String name, date;
void read()
{
Scanner s = new Scanner(System.in);
System.out.print("Enter Customer Name : ");
name = s.next();
System.out.print("Enter Date of Birth in dd/mm/yyyy : ");
date = s.next();
}
void display()
{
System.out.print("Output after String Tokenizing : ");
StringTokenizerst = new StringTokenizer(date, "/");
System.out.print(name);
while(st.hasMoreTokens())
System.out.print("," + st.nextToken());
}
public static void main(String args[])
{
customer c = new customer();
c.read();
c.display();
}
}
Output:
Enter Customer Name : Levitin
Enter Date of Birth in dd/mm/yyyy : 15/08/1947
Output after String Tokenizing : Levitin,15,08,1947
Department of CSE, JNNCE, Shimoga Page 11
Design and Analysis of AlgorithmsLaboratory (15CSL47)
3A. Write a Java program to read two integers a and b. Compute a/b and print, when b is not zero.
Raise an exception when b is equal to zero.
importjava.util.*;
classexcep
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter Numeratora : ");
int a = s.nextInt();
System.out.print("Enter Denominator b: ");
int b = s.nextInt();
if(b != 0)
{
}
else
{
double c = a/b;
System.out.print("Value of a/b is : " + c);
try
{
throw new ArithmeticException();
}
catch(ArithmeticException e)
{
System.out.println("Exception, Divide by Zero " + e);
}
}
}
}
Output:
Enter Numerator a : 10
Enter Denominator b : 2
Value of a/b is : 5.0
Enter Numerator a : 10
Enter Denominator b : 0
Exception, Divide by Zero
java.lang.ArithmeticException
Department of CSE, JNNCE, Shimoga Page 12
Design and Analysis of AlgorithmsLaboratory (15CSL47)
3B. Write a Java program that implements a multi-thread application that has three threads. First
thread generates a random integer for every 1 second; second thread computes the square of the
number and prints; third thread will print the value of cube of the number.
//filename should be threadmain
importjava.util.*;
classourthread extends Thread
{
intthreadnum;
staticintnum;
staticint flag=1;
ourthread(inti)
{
threadnum = i;
this.start();
}
public void run()
{
Random r = new Random();
while(true)
{
try
{
if(threadnum == 1 && flag==1)
{
num = r.nextInt(25);
System.out.println ("Thread 1 generated : " + num);
flag=2;
Thread.sleep(1000);
}
else if(threadnum == 2 && flag==2)
{
System.out.println ("Thread 2 Printing Square : " + (num * num ));
flag=3;
}
else if (threadnum == 3 && flag==3)
Department of CSE, JNNCE, Shimoga Page 13
Design and Analysis of AlgorithmsLaboratory (15CSL47)
{
System.out.println ("Thread 3 Printing Cube : " + (num * num * num));
flag=1;
}
}
catch (Exception e)
{
System.out.println ("Exception");
}
}
}
}
public class threadmain
{
public static void main(String arg[])
{
newourthread(1);
newourthread(2);
newourthread(3);
}
}
Output:
Thread 1 generated : 7
Thread 2 Printing Square :49
Thread 3 Printing Cube : 343
Thread 1 generated : 24
Thread 2 Printing Square : 576
Thread 3 Printing Cube : 13824
Thread 1 generated : 16
Thread 2 Printing Square : 256
Thread 3 Printing Cube :4096
Thread 1 generated : 10
Thread 2 Printing Square :100
Thread 3 Printing Cube :1000
Thread 1 generated : 20
Thread 2 Printing Square :400
Thread 3 Printing Cube :8000
Department of CSE, JNNCE, Shimoga Page 14
Design and Analysis of AlgorithmsLaboratory (15CSL47)
4. Sort a given set of n integer elements using Quick Sort method and compute its time complexity.
Run the program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the
time taken versus n on graph sheet. The elements can be read from a file or can be generatedusing
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.
importjava.util.*;
class quick
{
staticint a[ ];
staticint n;
staticint partition(int low, int high)
{
inti, j, t;
i = low+1;
j = high;
int pivot = a[low];
while(j>= i)
{
while((a[i]<=pivot) &&i<= high)
i++;
while(a[j]>pivot && j>low)
j--;
if(j>= i)
{
}
else
{
}
}
t = a[i];
a[i] = a[j];
a[j] = t;
t = a[low];
a[low] =a[j];
a[j] = t;
return j;
Department of CSE, JNNCE, Shimoga Page 15
Design and Analysis of AlgorithmsLaboratory (15CSL47)
}
static void quicksort(int low, int high)
{
if(low < high)
{
int p = partition(low, high);
quicksort(low, p-1);
quicksort(p+1, high);
}
}
static void read()
{
Scanner s = new Scanner(System.in);
Random r = new Random();
System.out.print("Enter value of n :");
n = s.nextInt();
a = new int[n+1];
for(inti=0; i<n; i++)
{
a[i] = n-i; //Worst Case
//a[i] = r.nextInt(n); //Avg Case
//a[i] = i; //Best Case
//a[i]=s.nextInt(); //manual input
}
}
static void display()
{
for(inti=0; i<n; i++)
System.out.println(a[i]);
}
public static void main(String args[])
{
read();
Department of CSE, JNNCE, Shimoga Page 16
Design and Analysis of AlgorithmsLaboratory (15CSL47)
System.out.println("Input Array");
display();
long start = System.nanoTime();
quicksort(0,n-1);
long end = System.nanoTime();
long diff = end-start;
System.out.println("Sorted Array");
display();
System.out.println("nTime in nanosecs : " + diff);
}
}
Output:
Run the program by varying Number of elements for Best Case, Worst Case and Average Cases and note
down the time take for execution. Plot the graph of N vs Time Taken for each Case.
N Best Case Worst Case Average Case
Department of CSE, JNNCE, Shimoga Page 17
Design and Analysis of AlgorithmsLaboratory (15CSL47)
5. Sort a given set of n integer elements using Merge Sort method and compute its timecomplexity.
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.
importjava.util.*;
classmergeclass
{
staticinta[],b[];
staticintn;
staticvoid merge(int low, int m, int h)
{
inti,j,k;
i=low; j=m+1; k=low;
while(i<=m && j <= h)
{
if(a[i] <= a[j])
{
}
else
{
}
k++;
}
b[k]=a[i];
i++;
b[k]=a[j];
j++;
while(i<=m)
{
b[k]=a[i];
k++;
i++;
}
while(j<=h)
{
Department of CSE, JNNCE, Shimoga Page 18
Design and Analysis of AlgorithmsLaboratory (15CSL47)
b[k]=a[j];
j++;
k++;
}
for(i=low; i<=h;i++)
a[i]=b[i];
}
staticvoidmergesort(int low, int h)
{
if(low<h)
{
int mid=(low+h)/2;
mergesort(low,mid);
mergesort(mid+1,h);
merge(low,mid,h);
}
}
staticvoid read()
{
Scanner s=newScanner(System.in);
Random r = newRandom();
System.out.print("Enter value of n:");
n=s.nextInt();
a=newint[n];
b=newint[n];
for(inti=0;i<n;i++)
{
a[i]=r.nextInt(n); //random avg case input
//a[i]=n-i; //reverse order input
//a[i]=i; //sorted input
//a[i]=s.nextInt(); //manual input
}
}
Department of CSE, JNNCE, Shimoga Page 19
Design and Analysis of AlgorithmsLaboratory (15CSL47)
staticvoid display()
{
for(inti=0;i<n;i++)
System.out.println(a[i]);
}
publicstaticvoid main(String s[])
{
read();
System.out.println("Input Array");
display();
long start=System.nanoTime();
mergesort(0,n-1);
long end= System.nanoTime();
System.out.println("Sorted Array");
display();
long diff=end-start;
System.out.println("Time in nano seconds:"+diff);
}
}
Output:
Run the program by varying Number of elements for Best Case, Worst Case and Average Cases and note
down the time take for execution. Plot the graph of N vs Time Taken for each Case.
N Best Case Worst Case Average Case
Department of CSE, JNNCE, Shimoga Page 20
Design and Analysis of AlgorithmsLaboratory (15CSL47)
6. Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming method (b)
Greedy method.
importjava.util.*;
classksack
{
staticintn,M,M1;
staticintw[],p[];
staticintf[][];
staticvoiddysack()
{
f=newint[n+1][M+1]; //table
for(inti=0;i<=n;i++)
{
for(int j=0;j<=M;j++)
{
if(i==0 || j==0)
f[i][j]=0;
elseif(w[i] > j)
f[i][j] = f[i-1][j];
else
}
}
f[i][j] = Math.max(f[i-1][j],f[i-1][j-w[i]]+p[i]);
System.out.println("Solution Table of Dynamic Method");
for(inti=0;i<=n;i++)
{
for(int j=0;j<=M;j++)
{
System.out.print("t" + f[i][j]);
}
System.out.println();
}
System.out.println("Solution with Dynamic Method is: " + f[n][M]);
}
staticvoiddyitems()
Department of CSE, JNNCE, Shimoga Page 21
Design and Analysis of AlgorithmsLaboratory (15CSL47)
{
int sol[] = newint[n+1];
for(inti=n;i>0;i--)
{
if(f[i][M] != f[i-1][M])
{
}
else
{
}
}
sol[i] = 1;
M = M-w[i];
sol[i] = 0;
System.out.print("The solution vector is:");
for(inti=1;i<=n;i++)
System.out.print(" "+sol[i]);
}
staticvoidgreedysack()
{
int sum=0;
double ratio[]=newdouble[n+1];
int sol[] = newint[n+1];
for(inti=1;i<=n;i++)
{
ratio[i]=(double)p[i]/w[i];
//profit to weight ratio
}
for (int q=1;q<=n;q++)
{
double max=0.0;
int k = 0; //to store max ratio index
for(inti=1;i<=n;i++)
{
if( (ratio[i] > max) && (sol[i] == 0))
{
Department of CSE, JNNCE, Shimoga Page 22
Design and Analysis of AlgorithmsLaboratory (15CSL47)
max=ratio[i];
k = i;
}
}
if(M1>= w[k])
{
}
else
{
}
}
sol[k] = 1; //selected
M1 = M1 - w[k];
sum = sum + p[k];
sol[k] = -1; //cannot select
for(inti=1;i<=n;i++)
{
if(sol[i] == -1)
sol[i] = 0;
}
System.out.println("nSolution with Greedy Method: "+sum);
System.out.print("The solution vector is:");
for(inti=1;i<=n;i++)
System.out.print(" "+sol[i]);
}
staticvoid read()
{
Scanner s=newScanner(System.in);
System.out.print("Enter num of items: ");
n=s.nextInt();
w=newint[n+1]; //weight
p=newint[n+1]; //profit
System.out.print("Enter Knapsack size: ");
M=s.nextInt();
M1=M;
Department of CSE, JNNCE, Shimoga Page 23
Design and Analysis of AlgorithmsLaboratory (15CSL47)
System.out.println("Enter Weights of all Items");
for(inti=1;i<=n;i++)
{
w[i]=s.nextInt();
}
System.out.println("Enter Profits of all Items");
for(inti=1;i<=n;i++)
{
p[i]=s.nextInt();
}
}
publicstaticvoid main(String args[])
{
read();
dysack();
dyitems();
greedysack();
}
}
Output-1:
Knapsack Capacity = 6
Enter num of items: 5
Enter Knapsack size: 6
Enter Weights of all Items
3 2 1 4 5
Enter Profits of all Items
25 20 15 40 50
Solution Table of Dynamic Method
0 0 0 0 0 0 0
0 0 0 25 25 25 25
Department of CSE, JNNCE, Shimoga Page 24
Design and Analysis of AlgorithmsLaboratory (15CSL47)
0 0 20 25 25 45 45
0 15 20 35 40 45 60
0 15 20 35 40 55 60
0 15 20 35 40 55 65
Solution with Dynamic Method is: 65
The solution vector is: 0 0 1 0 1
Solution with Greedy Method:60
The solution vector is: 1 1 1 0 0
Output-2:
Knapsack Capacity =5
Enter num of items: 4
Enter Knapsack size: 5
Enter Weights of all Items
2 1 3 2
Enter Profits of all Items
12 10 20 15
Solution Table of Dynamic Method
0 0 0 0 0 0
0 0 12 12 12 12
0 10 12 22 22 22
0 10 12 22 30 32
0 10 15 25 30 37
Solution with Dynamic Method is:37
The solution vector is: 1 1 0 1
Solution with Greedy Method:37
The solution vector is: 1 1 0 1
Department of CSE, JNNCE, Shimoga Page 25
Design and Analysis of AlgorithmsLaboratory (15CSL47)
7. From a given vertex in a weighted connected graph, find shortest paths to other vertices using
Dijkstra's algorithm. Write the program in Java.
importjava.util.*;
classdij
{
staticintn,src;
staticintc[][];
staticintvis[],dist[];
staticintcount;
staticvoid read()
{
Scanner s=newScanner(System.in);
System.out.print("Enter no of vertices:");
n=s.nextInt();
c=newint[n+1][n+1];
vis=newint[n+1];
dist=newint[n+1];
System.out.println("Enter cost matrix:");
for(inti=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
c[i][j]=s.nextInt();
}
}
System.out.print("Enter source node:");
src=s.nextInt();
}
staticvoidsolvedijkstras()
{
int u=0,min;
for(int j=1;j<=n;j++)
{
dist[j]=c[src][j];
}
dist[src]=0;
Department of CSE, JNNCE, Shimoga Page 26
Design and Analysis of AlgorithmsLaboratory (15CSL47)
vis[src]=1;
count=1;
while(count!=n)
{
min=9999;
for(int j=1;j<=n;j++)
{
if(dist[j]<min &&vis[j]!=1)
{
min=dist[j];
u=j;
}
}
vis[u]=1;
count++;
for(int j=1;j<=n;j++)
{
if((min + c[u][j] <dist[j]) &&vis[j]!=1)
{
dist[j]=min+c[u][j];
}
}
}
System.out.println("The shortest distance is:");
for(int j=1;j<=n;j++)
{
System.out.println(src+"--->"+j+" = "+dist[j]);
}
}
publicstaticvoid main(String s[])
{
read();
solvedijkstras();
}
}
Output:
Department of CSE, JNNCE, Shimoga Page 27
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Enter no of vertices:5
Enter cost matrix:
Enter source node:4
The shortest distance is:
4--->1 = 5
4--->2 = 2
4--->3 = 5
4--->4 = 0
4--->5 = 4
0 3 9999 7 9999
3 0 4 2 9999
9999 4 0 5 6
7 2 5 0 4
9999 9999 6 4 0
Department of CSE, JNNCE, Shimoga Page 28
Design and Analysis of AlgorithmsLaboratory (15CSL47)
8. Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's
algorithm. Use Union-Find algorithms in your program.
importjava.util.*;
classkruskal
{
staticintn;
staticintc[][];
staticvoidsolvekruskal()
{
int u=0,v=0,a=0,b=0,min=0;
int count=0,mincost=0;
int parent[]=newint[n+1];
while(count != n+1)
{
min=9999;
for(inti=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(c[i][j]<min && (i!=j))
{
min=c[i][j];
u=a=i;
v=b=j;
}
}
}
while(parent[u]!=0)
{
u=parent[u];
}
while(parent[v]!=0)
{
v=parent[v];
}
if(u!=v)
Design and Analysis of AlgorithmsLaboratory (15CSL47)
{
System.out.println(a+"--->"+b +" = "+ min);
parent[v]=u;
mincost = mincost+min;
}
c[a][b]=c[b][a]=9999;
count++;
}
System.out.println("mincost =" +mincost);
}
staticvoid read()
{
Scanner s=newScanner(System.in);
System.out.print("Enter no. of vertices: ");
n=s.nextInt();
c=newint[n+1][n+1];
System.out.println("Enter cost matrix:");
for(inti=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
c[i][j]=s.nextInt();
}
}
}
publicstaticvoid main(String s[])
{
read();
System.out.println("The Spanning Tree is: ");
solvekruskal();
}
}
Output:
Enter no of vertices:5
Enter cost matrix:
0 3 9999 7 9999
3 0 4 2 9999
Department of CSE, JNNCE, Shimoga Page 29
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 30
9999 4 0 5 6
7 2 5 0 4
9999 9999 6 4 0
The Spanning Tree is:
2--->4 = 2
1--->2 = 3
2--->3 = 4
4--->5 = 4
mincost =13
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 31
9. Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's
algorithm.
importjava.util.*;
class prim
{
staticintn;
staticintc[][];
staticvoidsolveprims()
{
int u=0,v=0,min=0;
int ne=0, mincost=0;
intelec[]=newint[n+1];
elec[1]=1;
while(ne != n-1)
{
min=9999;
for(inti=1;i<=n;i++)
{
for(intj=1;j<=n;j++)
{
if(elec[i]==1)
{
if(c[i][j]<min)
{
min=c[i][j];
u=i;
v=j;
}
}
}
}
if(elec[v]!=1)
{
System.out.println(u+"--->"+ v + " = " +min);
elec[v] = 1;
ne = ne+1;
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 32
mincost = mincost+min;
}
c[u][v] = c[v][u] = 9999;
}
System.out.println("nmincost = "+mincost);
}
staticvoid read()
{
Scanner s=newScanner(System.in);
System.out.print("Enter no. of vertices:");
n=s.nextInt();
c=newint[n+1][n+1];
System.out.println("Enter the cost matrix:");
for(inti=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
c[i][j] = s.nextInt();
}
}
}
publicstaticvoid main(String s[])
{
read();
System.out.println("The Spanning Tree is: ");
solveprims();
}
}
Output:
Enter no of vertices:5
Enter cost matrix:
0 3 9999 7 9999
3 0 4 2 9999
9999 4 0 5 6
7 2 5 0 4
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 33
9999 9999 6 4 0
The Spanning Tree is:
1--->2 = 3
2--->4 = 2
2--->3 = 4
4--->5 = 4
mincost =13
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 34
10. Write Java programs to
(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
importjava.util.*;
classfloyd
{
staticintn;
staticintd[][];
staticvoidsolvefloyd()
{
for(int k=1;k<=n;k++)
{
for(inti=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
d[i][j] = Math.min(d[i][j],d[i][k]+d[k][j]);
}
}
}
}
staticvoid read()
{
Scanner s=newScanner(System.in);
System.out.print("Enter no. of vertices :");
n=s.nextInt();
d=newint[n+1][n+1];
System.out.println("Enter the cost matrix:");
for(inti=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
d[i][j]=s.nextInt();
}
}
}
staticvoid display()
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 35
0 3 9999 7 9999
3 0 4 2 9999
9999 4 0 5 6
7 2 5 0 4
9999 9999 6 4 0
{
System.out.println("The least distance matrix is ");
for(inti=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
System.out.print(" "+d[i][j]);
}
System.out.println();
}
}
publicstaticvoid main(String s[])
{
read();
solvefloyd();
display();
}
}
Output:
Enter no. of vertices :5
Enter the cost matrix:
The least distance matrix is
0 3 7 5 9
3 0 4 2 6
7 4 0 5 6
5 2 5 0 4
9 6 6 4 0
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 36
10 (b) Implement Travelling Sales Person problem using Dynamic programming.
importjava.util.*;
class TSP
{
staticint n;
staticint c[][];
static String path[];
staticintnumpath=0;
static void findpath()
{
intminval = 9999;
intminindex = 0;
for(inti=0;i<numpath;i++)
{
intpathcost = 0;
int pre = 1, k = 1;
StringTokenizerst= new StringTokenizer(path[i],"->");
while(st.hasMoreTokens())
{
k = Integer.parseInt(st.nextToken());
pathcost= pathcost + c[pre][k];
pre = k;
}
pathcost = pathcost+c[k][1];
if(pathcost<minval)
{
minval = pathcost;
minindex = i;
}
}
path[minindex] = path[minindex] + "->1";
System.out.println("TSP PATH is "+path[minindex]);
}
staticintsolveTSP(int k, int set[],String pathseq)
{
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 37
int count = 0, value = 0;
int min = 999;
for(intj=1;j<=n;j++)
{
if(set[j] == 1)
count++;
}
if(count == 0)
{
}
else
{
path[numpath++] = pathseq;
return c[k][1];
for(inti=2; i<=n; i++)
{
if((i!=k) && (set[i]!=0))
{
set[i] = 0;
value = c[k][i] + solveTSP(i, set,pathseq+"->"+i);
if(value < min)
{
min = value;
}
set[i] = 1;
}
}
}
return min;
}
static void read()
{
Scanner s=new Scanner(System.in);
System.out.print("Enter no. of vertices: ");
n=s.nextInt();
c = new int[n+1][n+1];
int size = (int) Math.pow(2, n);
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 38
path = new String[size];
System.out.println("Enter cost matrix:");
for(inti=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
c[i][j]=s.nextInt();
}
}
}
public static void main(String s[])
{
read();
int set[] = new int [n+1];
for(inti=1;i<=n;i++)
set[i] = 1;
set[1]=0;
System.out.println("TSP Result is " + solveTSP(1,set,"1"));
findpath();
}
}
Output:
Enter no. of vertices: 5
Enter cost matrix:
0 2 0 6 1
1 0 4 4 2
5 3 0 1 5
4 7 2 0 1
2 6 3 6 0
TSP Result is 9
TSP PATH is 1->3->4->5->2->1
Enter no. of vertices: 4
Enter cost matrix:
0 10 15 20
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 39
5 0 9 10
6 13 0 12
8 8 9 0
TSP Result is 35
TSP PATH is 1->2->4->3->1
Enter no. of vertices: 4
Enter cost matrix:
0 10 15 20
10 0 35 25
15 35 0 30
20 35 30 0
TSP Result is 80
TSP PATH is 1->2->4->3->1
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 40
11. Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n positive
integers whose SUM is equal to a given positive integer d. For example, if S={1, 2, 5, 6, 8} and d= 9,
there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the given problem instance
doesn't have a solution.
importjava.util.*;
class subset
{
staticintn, d, count;
staticintset[], select[];
staticvoidsolvesubset(int m, int k, intsumr)
{
if(k >n+1)
return;
//m = partial sum of selected elements
//k = index of element being processed,
//sumr = sum of remaining elements of set
select[k] = 1;
if (m + set[k] == d)
{
//adding element k gives solution
count++;
System.out.println("nSolution " + count);
for (inti = 1; i<= k; i++)
{
if (select[i] == 1)
{
System.out.print("t" + set[i]);
}
}
}
elseif (k+1 <= n)
{
//can element be added?
if (m + set[k] + set[k+1] <= d)
{
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 41
solvesubset(m + set[k], k+1, sumr - set[k]);
}
}
if (k+1 <= n)
{
if ((m + sumr - set[k] >= d) && (m + set[k+1] <= d))
{
//try for solution without element k
select[k] = 0;
solvesubset(m, k+1, sumr - set[k]);
}
}
}
staticvoid read()
{
Scanner s = newScanner(System.in);
System.out.print("Enter num of Elements :");
n=s.nextInt();
set = newint[n+1];
select =newint[n+1];
System.out.print("Enter the Elements:");
for(inti=1;i<=n;i++)
{
set[i]=s.nextInt();
}
System.out.print("Enter Sum value :");
d = s.nextInt();
}
publicstaticvoid main(String args[])
{
intsumr = 0;
read();
for(inti=1;i<=n;i++)
{
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 42
sumr = sumr + set[i];
}
solvesubset(0, 1, sumr);
if(count==0)
System.out.println("No solution Exists");
}
}
Output:
Enter num of Elements :6
Enter the Elements :2 4 6 8 10 12
Enter Sum value :10
Solution 1
2 8
Solution 2
4 6
Solution 3
10
Enter num of Elements :6
Enter the Elements : 2 4 6 8 10 12
Enter Sum value :17
No solution Exists
Enter num of Elements :6
Enter the Elements : 2 4 6 8 10 12
Enter Sum value :28
Solution 1
2 4 10 12
Solution 2
2 6 8 12
Solution 3
4 6 8 10
Solution 4
6 10 12
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 43
12. Design and implement in Java to find all Hamiltonian Cycles in a connected undirected Graph
G of n vertices using backtracking principle.
importjava.util.*;
class ham
{
staticintn, start;
staticintG[][];
staticintx[];
staticbooleanfound = false;
staticvoid read()
{
Scanner s = newScanner(System.in);
System.out.print("Enter the Num of Nodes: ");
n = s.nextInt();
G = newint[n+1][n+1];
x = newint[n+1];
System.out.println("Enter the Adjacency Matrix: ");
for(inti=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
G[i][j]=s.nextInt();
}
}
System.out.print("Enter the Starting Node :");
start = s.nextInt();
}
staticvoidnextvalue(intk)
{
int j=0;
do
{
x[k]=(x[k]+1)%(n+1);
if(x[k]==0)
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 44
return;
if(G[x[k-1]][x[k]]==1)
{
for( j=1;j<=k-1;j++)
if(x[j]==x[k])
break;
}
}while(true);
}
if(j==k)
if(k<n || ((k==n) &&G[x[n]][x[1]]==1))
return;
staticvoidhamilton(int k)
{
x[1] = start;
do{
nextvalue(k);
if(x[k] == 0)
return;
if(k==n)
{
}
else
}
found = true;
System.out.println("Hamilton Cycle Path is");
for(inti=1;i<=n;i++)
System.out.print(x[i] + " -->");
System.out.println(" "+start);
hamilton(k+1);
while(true);
}
publicstaticvoid main(String args[])
{
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 45
read();
hamilton(2);
if(!found)
System.out.print("Hamilton Cycle doesnot Exists");
}
}
Output 1:
Enter the Num of Nodes: 8
Enter the Adjacency Matrix:
Enter the Starting Node:1
Hamilton Cycle Path is
1-->2-->8-->7-->6-->5-->4-->3-->1
Hamilton Cycle Path is
1-->3-->4-->5-->6-->7-->8-->2-->1
Output 2:
Enter the Num of Nodes: 8
Enter the Adjacency Matrix:
Enter the Starting Node:4
Hamilton Cycle Path is
4-->3-->1-->2-->8-->7-->6-->5-->4
0 1 1 0 0 0 1 0
1 0 1 0 0 0 0 1
1 1 0 1 0 1 0 0
0 0 1 0 1 0 0 0
0 0 0 1 0 1 0 0
0 0 1 0 1 0 1 0
1 0 0 0 0 1 0 1
0 1 0 0 0 0 1 0
0 1 1 0 0 0 1 0
1 0 1 0 0 0 0 1
1 1 0 1 0 1 0 0
0 0 1 0 1 0 0 0
0 0 0 1 0 1 0 0
0 0 1 0 1 0 1 0
1 0 0 0 0 1 0 1
0 1 0 0 0 0 1 0
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 46
Hamilton Cycle Path is
4-->5-->6-->7-->8-->2-->1-->3-->4
Output 3:
Enter the Num of Nodes: 5
Enter the Adjacency Matrix:
Enter the Starting Node:2
Hamilton Cycle doesnot Exists
0 1 0 0 1
1 0 1 1 1
0 1 0 1 0
0 1 1 0 0
1 1 0 0 0
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 47
Viva Questions
1) What is the time complexity of linear search?
Θ(n)
2) What is the time complexity of binary search?
Θ(log2n)
3) What is the major requirement for binary search?
The given list should be sorted.
4) What is binary search?
It is an efficient method of finding out a required item from a given list, provided
the list is in order.
The process is:
1. First the middle item of the sorted list isfound.
2. Compare the item with thiselement.
3. If they are equal search is complete.
4. If the middle element is greater than the item being searched, this process is repeated in the upper
half of the list.
5. If the middle element is lesser than the item being searched, this process is repeated in the lower
half of the list.
5) What is parental dominance?
The key at each node is greater than or equal to the keys at its children.
6) What is heap?
A heap can be defined as a binary tree with keys assigned to its nodes (
one key per node) provided the following two conditions are met:
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 48
1 The tree’s shape requirement – The binary tree is essentially complete ( or
simply complete), that is, all its levels are full except possibly the last level, where
only some rightmost leaves may be missing.
2. The parental dominance requirement – The key at each node is greater than or
equal to the keys at its children.
7) What is height of Binary tree?
It is the longest path from the root to any leaf.
8) What is the time complexity of heap sort?
Θ( n logn)
9) What is Merge Sort?
Merge sort is an O (n log n) comparison-based sorting algorithm.
Where the given array is divided into two equal parts. The left part of the array as
well as the right part of the array is sorted recursively. Later, both the left part and
right part are merged into a single sorted array.
10) Who invented Merge Sort?
John Von Neumann in 1945.
11) On which paradigm is it based?
Merge-sort is based on the divide-and-conquer paradigm.
12) What is the time complexity of merge sort?
n log n.
13) What is the space requirement of merge sort?
Space requirement: Θ(n) (not in-place).
14) When do you say an algorithm is stable and inplace?
Stable – if it retains the relative ordering. In –
place if it does not use extra memory.
15 ) Name the design strategy used in Selection Sort.
Brute force
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 49
16) Define Brute force strategy.
Brute force is a straight forward approach to solving a problem, usually
directly based on the problem’s statement and definitions of the concepts
involved.
17) What is the time complexity of Selection Sort algorithm?
(n2
)
18) Is Selection Sort Inplace?
Yes.
19) Is Selection Sort stable?
Yes.
20) Why is the name Selection Sort?
Algorithm selects the smallest number in the array and places it in its final
position the sorted array.
21) When is Selection Sort algorithm useful?
Selection Sort algorithm is useful for small inputs because it requires (n2
)
comparisons.
Selection Sort algorithm requires (n-1) swaps & hence (n) memory writes.
Thus it can be very useful if writes are the most expensive operation.
22) What are the drawbacks of Selection Sort?
Inefficient on large lists.
It requires same number of iterations no matter how well-organized the
array is.
It uses internal sorting, means it would require the entire array to be in
main memory.
23) When is a problem said to have overlapping sub problems?
A problem is said to have overlapping subproblems if it can be broken down into
subproblems which are reused multiple times. This is closely related to recursion.
24) What is principle of optimality?
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 50
The optimal solution to any instance of an optimization problem is composed of
optimal solutions to its sub instances.
25) Can knapsack problem be solved in any other technique?
It can be solved using many other techniques such as BruteForce, Greedy
technique, Branch and bound etc..
26) Mention few applications of dynamic programming.
Can be applied to find factorial, fibonacci numbers in which the required value may
depend on previously computed values.
To find the longest common substrings of the strings "ABAB", "BABA" and "ABBA"
are the strings "AB" and "BA" of length 2. Other common substrings are "A", "B" and
the empty string “”. etc..
27) Compare Dynamic programming and Divide and conquer.
Dynamic programming differs from the "Divide and Conquer" (D-and-C)
method in the fact that the problems solved by D-and-C can have many non-
overlapping subproblems - i.e, new subproblems may be generated when the method
is applied.
Both use recursion.
28) Who invented Dijkstra’s Algorithm?
Edsger Dijkstra invented this algorithm.
29) What is the other name for Dijkstra’s Algorithm?
Single Source Shortest Path Algorithm.
30) Which technique the Dijkstra’s algorithm is based on?
Greedy Technique.
31) What is the purpose of Dijkstra’s Algorithm?
To find the shortest path from source vertex to all other remaining vertices
32) Name the different algorithms based on Greedy technique.
Prim’s Algorithm, Kruskal’s algorithm
33) What is the constraint on Dijkstra’s Algorithm?
This algorithm is applicable to graphs with non-negative weights only.
34) What is a Weighted Graph?
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 51
A weighted graph is a graph with numbers assigned to its edges. These
numbers are called weights or costs.
35) What is a Connected Graph?
A graph is said to be connected if for every pair of its vertices u and v there is a
path from u to v.
36) What is the time complexity of Dijkstra’s algorithm?
For adjacency matrix, It is O(IVI*IVI)
For adjacency list with edges stored as min heap, it is O(IEIlogIVI)
37) Differentiate b/w Traveling Salesman Problem(TSP) and Dijkstra’s
Algorithm.
In TSP, given n cities with known distances b/w each pair , find the shortest tour
that passes through all the cities exactly once before returning to the starting city.
In Dijkstra’s Algorithm, find the shortest path from source vertex to all other
remaining vertices
38) Differentiate b/w Prim’s Algorithm and Dijkstra’s Algorithm?
Prim’s algorithm is to find minimum cost spanning tree.
Dijkstra’s algorithm is to find the shortest path from source vertex to all
other remaining vertices.
39) What are the applications of Dijkstra’s Algorithm?
It finds its application even in our day to day life while travelling. They
are helpful in routing applications.
40) Who was the inventor of the Quicksort?
C.A.R.HOARE, a British Scientist.
41) Which design strategy does Quicksort uses?
Divide and Conquer
42) What is Divide and Conquer Technique?
(I) Divide the instance of a problem into two or more smallerinstances
(II) Solve the smaller instances recursively
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 52
(III) Obtain solution to original instances by combining these solutions
43) What is the another name for Quicksort?
Partition Exchange Sort
44) What are the advantages and disadvantages?
Advantage: Fastest among all sorting algorithms Suitable when the input size is
very large
Disadvantage:
Heavily based on recursive sorting technique
It takes O (n* log n) time and O (log n) additional space due to
Recursion
45) Is Quicksort Stable as well as In place?
Not Stable but In place.
46) When do you say that a Quick sort having best case complexity?
When the pivot exactly divides the array into equal half
47) When do you say that Quick sort having worst case complexity?
When any one of the subarray is empty
48) How many more comparisons are needed for average case
compared to best case?
38% more
49) when do you say that the pivot element is in its final position?
When all the elements towards the left of pivot are <= pivot and all the
elements towards the right of pivot are >= pivot.
50) What is CLK_TCK?
macro defines the number of clock ticks per second which is available in the
TIME.H header file.
51) What technique does kruskal’s algorithm follow.
greedy technique
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 53
52) What is the time complexity.
With an efficient sorting algorithm, the time efficiency of an kruskal’s algorithm will be
in O(|E|log|E|).
53) Who is the inventor of kruskal’s algorithm.
Joseph Kruskal.
54) Which technique is used to solve BFS & DFS problems?
Decrease and Conquer
55) What is BFS traversal?
It proceeds in a concentric manner by visiting first all the vertices that are
adjacent to a starting vertex, then all unvisited vertices two edges apart from it and
so on , until all the vertices are in the same connected component as the starting
vertex are visited.
If there still remains unvisited vertices, the algorithm to be restarted at an
arbitrary vertex of another connected component of a graph.
56) What is DFS traversal?
Consider an arbitrary vertex v and mark it as visited on each iteration, proceed to an
unvisited vertex w adjacent to v. we can explore this new vertex depending upon its
adjacent information. This process continues until dead end is encountered.(no
adjacent unvisited vertex is available). At the dead end the algorithm backs up by one
edge and continues the process of visiting unvisited vertices. This process continues
until we reach the starting vertex.
57) What are Tree edge, Back edge & Cross edge ?
Tree edge: whenever a new unvisited vertex is reached for the first time, it is
attached as a child to the vertex from which it is being visited. Such an edge is called
a tree edge.
Back edge: An edge leading to a previously visited vertex other than its
immediate predecessor. Such an edge is called a back edge
Cross edge If an edge leading to a previously visited vertex other than its immediate
predecessor (i.e. its parent in the tree). Is encountered, the edge is noted as a cross
edge.
58) What are the various applications of BFS & DFS tree traversal
technique?
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 54
Application of BFS
Checking connectivity and checking acyclicity of a graph. Check
whether there is only one root in the BFS forest or not.
If there is only one root in the BFS forest, then it is connected graph otherwise
disconnected graph.
For checking cycle presence, we can take advantage of the graph's representation
in the form of a BFS forest, if the latter vertex does not have cross edge, then the graph
is acyclic.
Application of DFS
To check whether given graph is connected or not. To
check whether the graph is cyclic or not.
To find the spanning tree.
Topological sorting.
59) Which data structures are used in BFS & DFS tree traversal
technique?
We use Stack data structure to traverse the graph in DFS traversal. We
use queue data structure to traverse the graph in DFS traversal.
60) What are the efficiencies of BFS & DFS algorithms for Adjacency
matrix and adjacency list representation?
Adjacency matrices: Θ(V2
)
Adjacency linked lists: Θ(V+E)
61) Define set?
Set is unordered collection of distinct items.
62) Define power set?
The set of all subsets of a set is a power set.
63) Define squashed order?
Any subsets involving aj can be listed only after all the subsets involving
a1,…,aj-1(j=1,2,…,n-1)
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 55
64) What are the ways of generating subsets?
Decrease by constant
Bit string based algorithm
Minimal change algorithm
65) Explain time and space trade off strategy.
It is a strategy in which time efficiency can be achieved at the cost of
extra memory usage.
66) Which technique does the Horspool algorithm uses?
Input enhancement technique
67) Explain Input enhancement technique.
It is a technique in which the problem’s input is preprocessed in whole or in part
and the additional information stored is obtained to solve the problem.
68) What is a shift table?
It is a table that stores the shift information i.e it stores the distance of each
rightmost character in the first “m-1” characters of the pattern from the last character
of the pattern and stores the length of the pattern as the shift size if the character is
not present in the pattern.
69) Which is better Brute Force or Horspool algorithm for string
matching?
Horspool is better as it reduces the number of comparisons.
70) Differentiate between Brute-Force technique and Horspool
algorithm for string matching.
a) In brute-force, comparison starts from left where as in Horspool comparison starts from right.
b) In brute-force technique, if there is a character mismatch then we shift the pattern to the right by 1
position.
In Horspool, if there is a mismatch then the shift size is obtained from the shift
table and the pattern is shifted accordingly.
71) Differentiate between Horspool and Boyer -Moore algorithms.
Horspool algorithm uses only Shift table to obtain the shift
information.
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 56
Boyer - Moore algorithm uses 2 tables.
-Bad symbol shift table (same as the shift table used by Horspool).The shift
information of this table is known as d1
-Good suffix shift table
The shift information from this table is known as d2.
Shifting is done by taking max(d1,d2).
72) What is Dynamic Programming?
It is a technique for solving problems with overlapping sub problems.
73) What does Dynamic Programming have in common with Divide-
and-Conquer?
Both solve the problems by dividing the problem into sub problems.
Using the solutions of sub problems, the solutions for larger instance of the
problem can be obtained.
74) What is the Space & Time complexity of DP algo for Binomial
Coefficient C(n, k)?
Θ(nk)
75) What is a principle difference between the two techniques?
Only one instance of the sub problem is computed & stored. If the same
instance of sub problem is encountered, the solution is retrieved from the table and
never recomputed.
Very precisely re - computations are not preformed.
76) What is a spanning tree ?
A spanning tree of a weighted connected graph is its connected acyclic(no
cycles) subgraph (i.e. a tree)that contains all the vertices of a graph.
77) What is a minimum spanning tree ?
Minimum spanning tree of a connected graph is its spanning tree of smallest weight.
78) Prim’s algorithm is based on which technique.
Greedy technique.
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 57
79) State greedy technique for solving problem.
A greedy approach constructs a problem through a sequence of steps each
expanding a partially constructed solution obtained so far, untill the complete
solution is reached.
On each step the choice must be made as
Feasible: i.e. it has to satisfy the problem’s constraints.
Locally optimal: i.e. it has to be the best local choice among all feasible choices
available on that step.
Irrevocable: i.e. once made, it cannot be changed on subsequent steps of the
algorithm.
What are fringes and unseen vertices?
Fringes: vertices which are connected are called fringes.
Unseen vertices : vertices which are not adjacent are called unseen.
80) Name some of the application greedy technique
They are helpful in routing applications: In the case of network where large number
of computers are connected, to pass the data from one node to another node we can
find the shortest distance easily by this algorithm.
Communication Networks: Suppose there are 5 different cities and we want to
establish computer connectivity among them, then we take into the account of cost
factor for communication links.
Building a road network that joins n cities with minimum cost.
81) Does Prim’s Algorithm always yield a minimum spanning tree ?
Yes
82) What is the purose of Floyd’s algoreithm?
- To find the all pair shortestpath.
83) What is the time efficiency of floyd’s algorithm?
- It is same as warshall’s algorithm that isθ(n3
).
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 58
84) What is distance matrix?
- In which the element dij indicates the length of the path from ith
vertex to the jth
vertex.
85) What is shortest path?
- It is the path which is having shortest length among all possiblepaths.
86) warshall’s algorithm is optimization problem or non-optimization
problem ?
Non-optimization problem
87) For what purpose we use Warshall’s algorithm?
Warshall’s algorithm for computing the transitive closure of a directed graph
88) Warshall’s algorithm depends on which property?
Transitive property
89) what is the time complexity of Warshall’s algorithm?
Time complexity of warshall’s
90) what is hard problem?
Optimization problems which are having complexity of exponential or factorial.
91) hard problems can be solved by which method?
Back tracking and branch and bound techniques used for large instance of combinatorial
problems.
92) what is state space tree?
Constructing a tree of choices being made and processing is known as state-space- tree.
Root represents an initial state before the search for solution begins.
93) what are promising and non-promising state-space-tree?
Node which may leads to solution is called promising.
Node which doesn’t leads to solution is called non-promising.
(n3)
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 59
94) Differentiate between backtracking and Branch and Bound.
Branch and Bound uses Best first search technique and is applicable to optimization
problems.
Backtracking is applicable to non-optimization problems most of the times and
sometimes optimization problems. It uses DFS search technique.
95) In Backtracking what does the leaf node indicates?
It indicates either a non promising dead ends or solutions to the problem.
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 60
Additional Problem (Dynamic Programming & Greedy Algorithms)
I. Implement the job sequencing with deadlines problem using the fixed tuple size
formulation.
II. (a)
(b)
Implement the algorithm to compute roots of optimal
sub-trees. Implement the optimal binary search tree
problem.
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 61
Additional Problem ( Greedy Algorithms)
III.(a) Write an algorithm for partitioning problem. Partition problem is to determine
whether a given set can be partitioned into two subsets such that the sum of
elements in both subsets is same.
(b) Find a subset of a given set S = {S1, S2, , Sm} 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}. A suitable message is to be displayed if the
given problem instance doesn't have a solution.
(c) Given a value N, if we want to make change for N cents, and we have infinite
supply of each of S = {S1, S2,..... , Sm} valued coins, how many ways can we make the
change? The order of coins doesn‟t matter. For example, for N = 4 and S = {1, 2,
3}, there are four solutions: {1, 1, 1, 1}, {1, 1, 2}, {2, 2}, {1, 3}. So output should be 4.
For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2, 2, 2, 2, 2}, {2, 2, 3, 3}, {2,
2, 6}, {2, 3, 5} and {5, 5}. So the output should be 5.
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 62
Additional Problem (Graph Algorithms)
I. Perform the following operations on Disjoint set:
a) MAKE-SET
b) UNION
c) FIND-SET
d) INSERT
e) DELETE
f) SPLIT
g) Returns the minimum object in SET
II. Perform the following Union-by-Weight operations on a universe of 10 elements
(0-9, each initially in their own set). Draw the forest of trees that result. U(1,5);
U(3,7); U(1,4);U(5,7); U(0,8); U(6,9); U(3,9). If the sets have equal weight, use the
root with the smaller value as the root of the new set.
III. Let G be a connected graph of order n. Write an algorithm for finding maximum
number of Cut•vertices that G can contain. Cut•vertex is a vertex which when
removed from the graph splits it into two disconnected components.
IV. An Euler circuit for an undirected graph is a path that starts and ends at the same
vertex and uses each edge exactly once. A connected undirected graph G has an
Euler circuit. If and only If energy vertex is of even degree. Give an algorithm and
implement to find the Euler Circuit in a graph with e edges provided one exists.
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 63
Additional Problem (Other Techniques)
I. Implement N Queen's problem.
II. Implement Sudoku problem.
III. Design an efficient solution for tower of Hanoi problem.
IV. Implement 0/1 Knapsack problem.
V Implement the travelling salesman problem (TSP).
VI. Given a rod of length n inches and an array of prices that contains prices
of all pieces of size smaller than n. Determine the maximum value
obtainable by cutting up the rod and selling the pieces. For example, if
length of the rod is 8 and the values of different pieces are given as
following, then the maximum obtainable value is 22 (by cutting in two
pieces of lengths 2 and 6)
Length | 1 2 3 4 5 6 7 8
----------------------------------------------------
- Price | 1 5 8 9 10 17 17 20
VII Implement the Coin change problem.
VIII. Design the Graph coloring problem
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 64
MULTIPLE CHOICE QUESTIONS
1. You have to sort a list L consistnn of a sorted list followed by a few random el- ements.
Which of the followinn sortnn methods would be especially suitable for such a task?
A) Bubble sort
B) Selecton sort
C) Quick sort
D) Inserton sort
2. A technique for direct search is .......................................
A) Binary Search
B) Linear Search
C) Tree Search D) Hashinn
3. The searchinn technique that takes O(1) tme to fnd a data is
(A) Linear Search
(B) Binary Search
(C) Hashinn
(D) Tree Search
4. The number of interchannes required to sort 5, 1, 6, 2 4 in ascendinn order usinn
Bubble Sort is
(A) 6
(B) 5
(C) 7
(D) 8
5. The postix form of the expression (A + B) ∗ (C ∗ D − E) ∗ F/G is
(A) AB + CD ∗ E − FG/ ∗ ∗
(B) AB + CD ∗ E − F ∗ ∗G/
(C) AB + CD ∗ E − ∗F ∗ G/
(D) AB + CDE ∗ − ∗ F ∗ G/
6. The complexity of multplyinn two matrices of order m*n and n*p is
(A) mnp
(B) mp
(C) mn
(D) np
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 65
7. In worst case Quick Sort has order
(A) O (n lon n)
(B) O (lon n)
(C) O (n 2 /2)
(D) O (n 2/4)
8. A full binary tree with 2n+1 nodes contain
(A) n leaf nodes (B) n non-leaf nodes (C) n-1 leaf nodes (D) n-1 non-leaf nodes
9. A linear list of elements in which deleton can be done from one end (front) and
inserton can take place only at the other end (rear) is known asa
(A) queue.
(B) stack.
(C) tree.
(D) linked list.
10. A sort which relatvely passes throunh a list to exchanne the frst element with any
element less than it and thenrepeats with a new frst element is called
(A) inserton sort.
(B) selecton sort.
(C) heap sort.
(D) quick sort.
11. Which of the followinn sortnn alnorithms does not have a worst case runninn tme of
O(n 2 ) ?
(A) Inserton sort
(B) Merne sort
(C) Quick sort
(D) Bubble sort
12. Consider a linked list of n elements. What is the tme taken to insert an element after an
element pointed by some pointer?
(A) O (1)
(B) O ( lon 2 n )
(C) O (n)
(D) O ( n lon 2 n )
13. The data structure required for Breadth First Traversal on a nraph is
(A) queue
(B) stack
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 66
(C) array
(D) tree
14. In a circular linked list
(A) components are all linked tonether in some sequentalmanner.
(B) there is no beninninn and no end.
(C) components are arranned hierarchically.
(D) forward and backward traversal within the list is permited.
15. The quick sort alnorithm exploit ————– desinn technique
(A) Greedy
(B) Dynamic pronramminn
(C) Divide and Conquer
(D) Backtracking
16. The number of diferent directed trees with 3 nodes are
(A) 2
(B) 3
(C) 4
(D) 5
17. The data structure required to evaluate a postix expression is
(A) queue
(B) stack
(C) array
(D) linked-list
18. The data structure required to check whether an expression contains balanced
parenthesis is
(A) Stack
(B) Queue
(C) Tree
(D) Array
19. The complexity of searchinn an element from a set of n elements usinn Binary search
alnorithm is
(A) O(n)
(B) O(lon n)
(C) O(n 2 )
(D) O(n lon n)
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 67
20. What data structure would you mostly likely see in a nonrecursive implementaton ofa
recursive alnorithm?
(A) Stack
(B) Linked list
(C) Queue
(D) Trees
Which of the followinn sortnn methods would be most suitable for sortnn a list which is
almost sorted ?
(A) Bubble Sort
(B) Inserton Sort
(C) Selecton Sort
(D) Quick Sort
22. A binary tree of depth ”d” is an almost complete binary tree if
(A) Each leaf in the tree is either at level ”d” or at level”d-1”
(B) For any node ”n” in the tree with a rinht descendent at level ”d” all theleft descendent
of ”n” that are leaves, are also at level ”d”
(C) Both (A) & (B)
(D) None of the above
23. If the address of A[1][1] and A[2][1] are 1000 and 1010 respectvely and each ele-
ment occupies 2 bytes then the array has been stored in —————order.
(A) row major
(B) column major
(C) matrix major
(D) none of these
24. An adjacency matrix representaton of a nraph cannot contain informaton of :
(A) nodes
(B) ednes
(C) directon of ednes
(D) parallel ednes
25. O(N) (linear tme) is beter than O(1) constant tme.
(A) True
(B) False
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 68
26. The best averane behaviour is shown by
(A) Quick Sort
(B) Merne Sort
(C) Inserton Sort
(D) Heap Sort
27. A queue is a,
(A) FIFO (First In First Out) list.
(C) Ordered array.
(B) LIFO (Last In First Out) list.
(D) Linear tree.
28. Which data structure is needed to convert infx notaton to postixnotaton?
(A) Branch
(B) Queue
(C) Tree
(D) Stack
29. Consider that n elements are to be sorted. What is the worst case tme complexity of
Bubble sort?
(A) O(1)
(C) O(n)
(B) O(lon 2 n)
(D) O(n 2 )
30. A characteristc of the data that binary search uses but the linear search innores is the
——————-.
(A) Order of the elements of thelist.
(B) Lennth of the list.
(C) Maximum value in list.
(D) Type of elements of the list.
31. In Breadth First Search of Graph, which of the followinn data structure is used?
(A) Stack.
(B) Queue.
(C) Linked List.
(D) None of the above.
32. In order to net the contents of a Binary search tree in ascendinn order, one has to
traverse it in
Design and Analysis of AlgorithmsLaboratory (15CSL47)
Department of CSE, JNNCE, Shimoga Page 69
(A) pre-order.
(B) in-order.
(C) post order.
(D) not possible.
33. In binary search, averane number of comparison required for searchinn an element in a
list if n numbers is
(A) lon 2 n .
(B) n / 2 .
(C) n.
(D) n - 1.
34. The worst case of quick sort has order
(A) O(n 2 )
(B) O(n)
(C) O (n lon 2 n)
(D) O (lon 2 n)
35. The tme required to delete a node x from a doubly linked list havinn n nodes is
(A) O (n)
(B) O (lon n)
(C) O (1)
(D) O (n lon n)

More Related Content

Similar to Daa final 2019 20

66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
Laura Popovici
 
PPS Manual_AY_2021-22 I & II Sem.pdf
PPS Manual_AY_2021-22 I & II Sem.pdfPPS Manual_AY_2021-22 I & II Sem.pdf
PPS Manual_AY_2021-22 I & II Sem.pdf
SugnanaraoM
 
Project MLExAI: Machine Learning Experiences in AI
Project MLExAI: Machine Learning Experiences in AIProject MLExAI: Machine Learning Experiences in AI
Project MLExAI: Machine Learning Experiences in AI
butest
 
Project MLExAI: Machine Learning Experiences in AI
Project MLExAI: Machine Learning Experiences in AIProject MLExAI: Machine Learning Experiences in AI
Project MLExAI: Machine Learning Experiences in AI
butest
 
CS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab ManualCS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab Manual
pkaviya
 
Three dimensional modeling
Three dimensional modelingThree dimensional modeling
Three dimensional modeling
HCS
 
Cse 7th-sem-machine-learning-laboratory-csml1819
Cse 7th-sem-machine-learning-laboratory-csml1819Cse 7th-sem-machine-learning-laboratory-csml1819
Cse 7th-sem-machine-learning-laboratory-csml1819
HODCSE21
 
Developing Projects & Research
Developing Projects & ResearchDeveloping Projects & Research
Developing Projects & Research
Thomas Mylonas
 
Database management system lLABMANUALpdf
Database management system lLABMANUALpdfDatabase management system lLABMANUALpdf
Database management system lLABMANUALpdf
BhagyavantRajapure
 

Similar to Daa final 2019 20 (20)

Cn lab manual sb 19_scsl56 (1)
Cn lab manual sb 19_scsl56 (1)Cn lab manual sb 19_scsl56 (1)
Cn lab manual sb 19_scsl56 (1)
 
66781291 java-lab-manual
66781291 java-lab-manual66781291 java-lab-manual
66781291 java-lab-manual
 
Dsp lab manual
Dsp lab manualDsp lab manual
Dsp lab manual
 
PPS Manual_AY_2021-22 I & II Sem.pdf
PPS Manual_AY_2021-22 I & II Sem.pdfPPS Manual_AY_2021-22 I & II Sem.pdf
PPS Manual_AY_2021-22 I & II Sem.pdf
 
Project MLExAI: Machine Learning Experiences in AI
Project MLExAI: Machine Learning Experiences in AIProject MLExAI: Machine Learning Experiences in AI
Project MLExAI: Machine Learning Experiences in AI
 
Project MLExAI: Machine Learning Experiences in AI
Project MLExAI: Machine Learning Experiences in AIProject MLExAI: Machine Learning Experiences in AI
Project MLExAI: Machine Learning Experiences in AI
 
CS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab ManualCS8662 Mobile Application Development Lab Manual
CS8662 Mobile Application Development Lab Manual
 
Three dimensional modeling
Three dimensional modelingThree dimensional modeling
Three dimensional modeling
 
Hdllab1
Hdllab1Hdllab1
Hdllab1
 
Cse 7th-sem-machine-learning-laboratory-csml1819
Cse 7th-sem-machine-learning-laboratory-csml1819Cse 7th-sem-machine-learning-laboratory-csml1819
Cse 7th-sem-machine-learning-laboratory-csml1819
 
Programming paradigms
Programming paradigmsProgramming paradigms
Programming paradigms
 
SE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUSSE-IT JAVA LAB SYLLABUS
SE-IT JAVA LAB SYLLABUS
 
Developing Projects & Research
Developing Projects & ResearchDeveloping Projects & Research
Developing Projects & Research
 
AIML-MODULE1.pdf
AIML-MODULE1.pdfAIML-MODULE1.pdf
AIML-MODULE1.pdf
 
Database management system lLABMANUALpdf
Database management system lLABMANUALpdfDatabase management system lLABMANUALpdf
Database management system lLABMANUALpdf
 
A case study of LEGO Mindstorms suitability for artificial intelligence and...
A case study of LEGO Mindstorms   suitability for artificial intelligence and...A case study of LEGO Mindstorms   suitability for artificial intelligence and...
A case study of LEGO Mindstorms suitability for artificial intelligence and...
 
Defense
DefenseDefense
Defense
 
Object oriented programming using java
Object oriented programming using javaObject oriented programming using java
Object oriented programming using java
 
Data Analyst Tasks to do the internship.pdf
Data Analyst Tasks to do the internship.pdfData Analyst Tasks to do the internship.pdf
Data Analyst Tasks to do the internship.pdf
 
OOSE Unit 3 PPT.ppt
OOSE Unit 3 PPT.pptOOSE Unit 3 PPT.ppt
OOSE Unit 3 PPT.ppt
 

Recently uploaded

Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 

Recently uploaded (20)

Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 

Daa final 2019 20

  • 1. JAWAHARLAL NEHRU NATIONAL COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING A Laboratory Manual On DESIGN AND ANALYSISOF ALGORITHMS LABoRATORY (18CSL47) Prepared By Dr. RAVINDRA S. Mr. NARENDRA KUMAR S Associate Professor Assistant Professor Dept. of CSE Dept. of CSE
  • 2. Vision To be one of the pre-eminent departments to provide technical and knowledge based education, utilizing the potential of Computer Science & Engineering to meet the ever changing needs of industry and society. Mission M1: Mould the students to meet the emerging challenges of industry and society. M2: Emphasizing on research M3 Effective industry interaction for the development of state of the art technological infrastructure and faculty component. JAWAHARLAL NEHRU NATIONAL COLLEGE OF ENGINEERING Department of Computer Science and Engineering Program Educational Objectives Graduates of the Program: PEO -1 Would be able to identify real world problems and solve them effectively using comprehensive knowledge of computer science. PEO -2 Would be able to become entrepreneur, pursue higher education and carry out research. PEO -3 To work in changing environment with ethical and social responsibilities. Program Specific Outcomes PSO -1 Apply concepts in the core areas of Computer Science & Engineering – Networking, Data Structures, Computer Architecture, Mathematical Modeling and System Programming to address technical issues. PSO -2 Design and develop computer based systems by applying standard practices and principles using appropriate tools and programming languages for real world problems.
  • 3. Program Outcomes PO 1 Apply the knowledge of mathematics, science, engineering fundamentals, and an engineering specialization to the solution of complex engineering problems. PO 2 Identify, formulate, review research literature, and analyze complex engineering problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences. PO 3 Design solutions for complex engineering problems and design system components or processes that meet the specified needs with appropriate consideration for the public health and safety, and the cultural, societal, and environmental considerations. PO 4 Use research-based knowledge and research methods including design of experiments, analysis and interpretation of data, and synthesis of the information to provide valid conclusions. PO 5 Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools including prediction and modeling to complex engineering activities with an understanding of the limitations. PO 6 Apply reasoning informed by the contextual knowledge to assess societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice. PO 7 Understand the impact of the professional engineering solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development. PO 8 Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering practice. PO 9 Function effectively as an individual, and as a member or leader in diverse teams, and in multidisciplinary settings. PO 10 Communicate effectively on complex engineering activities with the engineering community and with society at large, such as, being able to comprehend and write effective reports and design documentation, make effective presentations, and give and receive clear instructions. PO 11 Demonstrate knowledge and understanding of the engineering and management principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in multidisciplinary environments. PO 12 Recognize the need for, and have the preparation and ability to engage in independent and life-long learning in the broadest context of technological change.
  • 4. Syllabus DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY Sub. Code: 17CSL47 IA Marks 40 Number of Lecture Hours/Week: 01 I + 02 P Exam Hours 03 Total Hours: 40 Exam Marks : 60 CREDITS 02 Design, develop, and implement the specified algorithms for the following problems using Java language under LINUX /Windows environment. Netbeans/Eclipse IDE tool can be used for development and demonstration. 1. A. Create a Java class called Student with the following details as variables within it. (i) USN (ii) Name (iii) Branch (iv) Phone Write a Java program to create nStudent objects and print the USN, Name, Branch, and Phoneof these objects with suitable headings. B. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods to demonstrate its working. 2. A. Design a superclass called Staff with details as StaffId, Name, Phone, Salary. Extend this class by writing three subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write a Java program to read and display at least 3 staff objects of all three categories. B. Write a Java class called Customer to store their name and date_of_birth. The date_of_birth format should be dd/mm/yyyy. Write methods to read customer data as <name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using StringTokenizer class considering the delimiter character as “/”. 3. A. Write a Java program to read two integers a and b. Compute a/b and print, when b is not zero. Raise an exception when b is equal to zero. B. Write a Java program that implements a multi-thread application that has three threads. First thread generates a random integer for every 1 second; second thread computes the square of the number and prints; third thread will print the value of cube of thenumber.
  • 5. 4. Sort a given set of n integer elements using Quick Sort method and compute its time complexity. Run the program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the time taken versus 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. 5. Sort a given set of n integer elements using Merge Sort method and compute its time complexity. Run the program for varied values of n> 5000, and record the time taken to sort. Plot a graph of the time taken versus 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. 6. Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming method (b) Greedy method. 7. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm. Write the program in Java. 8. Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's algorithm. Use Union-Find algorithms in your program. 9. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm. 10. Write Java programs to (a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm. (b) Implement Travelling Sales Person problem using Dynamic programming. 11. Design and implement in Java to find a subset of a given set S = {Sl, S2, ,Sn} of n positive integers whose SUM is equal to a given positive integer d. For example, if S ={1, 2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the given problem instance doesn't have a solution. 12. Design and implement in Java to find all Hamiltonian Cycles in a connected undirected Graph G of n vertices using backtracking principle.
  • 6.
  • 7. Design and Analysis of AlgorithmsLaboratory (17CSL47) Department of CSE, JNNCE, Shimoga Page 1 1A.Create a Java class called Student with the following details as variables within it. (i) USN (ii) Name (iii) Branch (iv) Phone Write a Java program to create n Student objects and print the USN, Name, Branch, and Phone of these objects with suitable headings. importjava.util.*; public class student { String usn; String name; String branch; long phone; public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter number of Students:"); int n = scan.nextInt(); students[]=new student[n]; for(inti=0;i<n;i++) s[i]=new student(); for(inti=0;i<n;i++) { System.out.print("Enter usn:"); s[i].usn = scan.next(); System.out.print("Enter name:"); s[i].name = scan.next(); System.out.print("Enter branch:"); s[i].branch = scan.next(); System.out.print("Enter phone number:"); s[i].phone = scan.nextLong(); } System.out.println("USN" + "tNAME" + "tBRANCH" + "tPHONE"); for(inti=0;i<n;i++) { System.out.println(s[i].usn + "t" + s[i].name + "t" + s[i].branch + "t" + s[i].phone);
  • 8. Design and Analysis of AlgorithmsLaboratory (15CSL47) } } Department of CSE, JNNCE, Shimoga Page 2 } Output: Enter number of Students:3 Enter usn:4JN18CS001 Enter name:Levitin Enter branch:CSE Enter phone number:9988776655 Enter usn:4JN18EC002 Enter name:Sahni Enter branch:ECE Enter phone number:7788994455 Enter usn:4JN18IS004 Enter name:Rama Enter branch:ISE Enter phone number:8899552233 USN NAME BRANCH PHONE 4JN18CS001 Levitin CSE 9988776655 4JN18EC002 Sahni ECE 7788994455 4JN18IS004 Rama ISE 8899552233
  • 9. Department of CSE, JNNCE, Shimoga Page 3 Design and Analysis of AlgorithmsLaboratory (15CSL47) 1B. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods to demonstrate its working. importjava.util.*; classstack { staticintst[]; staticint top = -1; staticintsz; static void push() { Scanner s = new Scanner(System.in); System.out.print("Enter element to push : "); int n = s.nextInt(); if(top+1 >= sz) { } else { } } System.out.println("Overflow"); st[++top] = n; static void pop() { if(top<0) { } else { } } System.out.println("Underflow"); int p = st[top]; top = top-1; System.out.println("Element poped : " + p); static void display() { System.out.println("Stack elements are:"); for(inti = top; i>= 0; i--) { System.out.println(st[i]);
  • 10. Department of CSE, JNNCE, Shimoga Page 4 Design and Analysis of AlgorithmsLaboratory (15CSL47) } } public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.print("Enter the size of the stack : "); sz=s.nextInt(); st=new int[sz]; while(true) { System.out.println("1:push 2:pop 3:display"); int c=s.nextInt(); switch(c) { case 1: push(); break; case 2: pop(); break; case 3:display(); break; default: System.out.println("invalid"); System.exit(0); } } } } Output: Enter the size of the stack : 4 1:push 2:pop 3:display 2 Underflow 1:push 2:pop 3:display 1 Enter element to push : 5 1:push 2:pop 3:display 1 Enter element to push : 10 1:push 2:pop 3:display 1 Enter element to push : 20
  • 11. Department of CSE, JNNCE, Shimoga Page 5 Design and Analysis of AlgorithmsLaboratory (15CSL47) 1:push 2:pop 3:display 1 Enter element to push : 25 1:push 2:pop 3:display 1 Enter element to push : 30 Overflow 1:push 2:pop 3:display 3 Stack elements are: 25 20 10 5 1:push 2:pop 3:display 2 Element poped : 25 1:push 2:pop 3:display 3 Stack elements are: 20 10 5 1:push 2:pop 3:display
  • 12. Department of CSE, JNNCE, Shimoga Page 6 Design and Analysis of AlgorithmsLaboratory (15CSL47) 2A. Design a superclass called Staff with details as StaffId, Name, Phone, Salary. Extend this class by writing three subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write a Java program to read and display at least 3 staff objects of all three categories. //file name should be staffmain importjava.util.*; class staff { String staffid; String name; long phone; double salary; static Scanner s; voidread_staff() { Scanner s = new Scanner(System.in); System.out.print("Enter Staffid: "); staffid = s.next(); System.out.print("Enter Name: "); name = s.next(); System.out.print("Enter Phone: "); phone = s.nextLong(); System.out.print("Enter Salary: "); salary = s.nextDouble(); } } class Teaching extends staff { String domain; int pub; voidread_teaching() { Scanner s = new Scanner(System.in); System.out.print("Enter Domain: ");
  • 13. Department of CSE, JNNCE, Shimoga Page 7 Design and Analysis of AlgorithmsLaboratory (15CSL47) domain=s.next(); System.out.print("Enter Publication: "); pub=s.nextInt(); } void display() { System.out.println(staffid +"t"+ name +"t"+ phone +"t"+ salary +"t"+ domain +"t"+ pub); } } class Technical extends staff { String skills; voidread_technical() { Scanner s = new Scanner(System.in); System.out.print("Enter Skills: "); skills=s.next(); } void display() { System.out.println(staffid +"t"+ name +"t"+ phone +"t"+ salary +"t"+ skills); } } class Contract extends staff { int period; voidread_contract() { Scanner s = new Scanner(System.in); System.out.print("Enter Period: "); period=s.nextInt(); } void display() { System.out.println(staffid +"t"+ name +"t"+ phone +"t"+ salary +"t"+ period); }
  • 14. Department of CSE, JNNCE, Shimoga Page 8 Design and Analysis of AlgorithmsLaboratory (15CSL47) } classstaffmain { public static void main(String ss[]) { Teaching t1 = new Teaching(); Technical t2 = new Technical(); Contract t3 = new Contract(); t1.read_staff(); t1.read_teaching(); t2.read_staff(); t2.read_technical(); t3.read_staff(); t3.read_contract(); System.out.println("Staffid Name phone salary Domain publication"); t1.display(); System.out.println("Staffid Name phone salary Skills"); t2.display(); System.out.println("Staffid Name phone salary Contract"); t3.display(); } } Output: Enter Staffid: 1 Enter Name: Levitin Enter Phone: 9988776655 Enter Salary: 10000 Enter Domain: CSE Enter Publication: 12 Enter Staffid: 2 Enter Name: Sahni Enter Phone: 8877996655 Enter Salary: 15000 Enter Skills: writing Enter Staffid: 3 Enter Name: Rama
  • 15. Department of CSE, JNNCE, Shimoga Page 9 Design and Analysis of AlgorithmsLaboratory (15CSL47) Enter Phone: 7788994455 Enter Salary: 20000 Enter Period: 2 Staffid Name phone salary Domain publication 1 Levitin 9988776655 10000.0 CSE 12 Staffid Name phone salary Skills 2 Sahni 8877996655 15000.0 writing Staffid 3 Name Rama phone 7788994455 salary 20000.0 Contract 2
  • 16. Department of CSE, JNNCE, Shimoga Page 10 Design and Analysis of AlgorithmsLaboratory (15CSL47) 2B. Write a Java class called Customer to store their name and date_of_birth. The date_of_birth format should be dd/mm/yyyy. Write methods to read customer data as <name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using StringTokenizer class considering the delimiter character as “/”. importjava.util.*; public class customer { String name, date; void read() { Scanner s = new Scanner(System.in); System.out.print("Enter Customer Name : "); name = s.next(); System.out.print("Enter Date of Birth in dd/mm/yyyy : "); date = s.next(); } void display() { System.out.print("Output after String Tokenizing : "); StringTokenizerst = new StringTokenizer(date, "/"); System.out.print(name); while(st.hasMoreTokens()) System.out.print("," + st.nextToken()); } public static void main(String args[]) { customer c = new customer(); c.read(); c.display(); } } Output: Enter Customer Name : Levitin Enter Date of Birth in dd/mm/yyyy : 15/08/1947 Output after String Tokenizing : Levitin,15,08,1947
  • 17. Department of CSE, JNNCE, Shimoga Page 11 Design and Analysis of AlgorithmsLaboratory (15CSL47) 3A. Write a Java program to read two integers a and b. Compute a/b and print, when b is not zero. Raise an exception when b is equal to zero. importjava.util.*; classexcep { public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.print("Enter Numeratora : "); int a = s.nextInt(); System.out.print("Enter Denominator b: "); int b = s.nextInt(); if(b != 0) { } else { double c = a/b; System.out.print("Value of a/b is : " + c); try { throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("Exception, Divide by Zero " + e); } } } } Output: Enter Numerator a : 10 Enter Denominator b : 2 Value of a/b is : 5.0 Enter Numerator a : 10 Enter Denominator b : 0 Exception, Divide by Zero java.lang.ArithmeticException
  • 18. Department of CSE, JNNCE, Shimoga Page 12 Design and Analysis of AlgorithmsLaboratory (15CSL47) 3B. Write a Java program that implements a multi-thread application that has three threads. First thread generates a random integer for every 1 second; second thread computes the square of the number and prints; third thread will print the value of cube of the number. //filename should be threadmain importjava.util.*; classourthread extends Thread { intthreadnum; staticintnum; staticint flag=1; ourthread(inti) { threadnum = i; this.start(); } public void run() { Random r = new Random(); while(true) { try { if(threadnum == 1 && flag==1) { num = r.nextInt(25); System.out.println ("Thread 1 generated : " + num); flag=2; Thread.sleep(1000); } else if(threadnum == 2 && flag==2) { System.out.println ("Thread 2 Printing Square : " + (num * num )); flag=3; } else if (threadnum == 3 && flag==3)
  • 19. Department of CSE, JNNCE, Shimoga Page 13 Design and Analysis of AlgorithmsLaboratory (15CSL47) { System.out.println ("Thread 3 Printing Cube : " + (num * num * num)); flag=1; } } catch (Exception e) { System.out.println ("Exception"); } } } } public class threadmain { public static void main(String arg[]) { newourthread(1); newourthread(2); newourthread(3); } } Output: Thread 1 generated : 7 Thread 2 Printing Square :49 Thread 3 Printing Cube : 343 Thread 1 generated : 24 Thread 2 Printing Square : 576 Thread 3 Printing Cube : 13824 Thread 1 generated : 16 Thread 2 Printing Square : 256 Thread 3 Printing Cube :4096 Thread 1 generated : 10 Thread 2 Printing Square :100 Thread 3 Printing Cube :1000 Thread 1 generated : 20 Thread 2 Printing Square :400 Thread 3 Printing Cube :8000
  • 20. Department of CSE, JNNCE, Shimoga Page 14 Design and Analysis of AlgorithmsLaboratory (15CSL47) 4. Sort a given set of n integer elements using Quick Sort method and compute its time complexity. Run the program for varied values of n> 5000 and record the time taken to sort. Plot a graph of the time taken versus n on graph sheet. The elements can be read from a file or can be generatedusing 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. importjava.util.*; class quick { staticint a[ ]; staticint n; staticint partition(int low, int high) { inti, j, t; i = low+1; j = high; int pivot = a[low]; while(j>= i) { while((a[i]<=pivot) &&i<= high) i++; while(a[j]>pivot && j>low) j--; if(j>= i) { } else { } } t = a[i]; a[i] = a[j]; a[j] = t; t = a[low]; a[low] =a[j]; a[j] = t; return j;
  • 21. Department of CSE, JNNCE, Shimoga Page 15 Design and Analysis of AlgorithmsLaboratory (15CSL47) } static void quicksort(int low, int high) { if(low < high) { int p = partition(low, high); quicksort(low, p-1); quicksort(p+1, high); } } static void read() { Scanner s = new Scanner(System.in); Random r = new Random(); System.out.print("Enter value of n :"); n = s.nextInt(); a = new int[n+1]; for(inti=0; i<n; i++) { a[i] = n-i; //Worst Case //a[i] = r.nextInt(n); //Avg Case //a[i] = i; //Best Case //a[i]=s.nextInt(); //manual input } } static void display() { for(inti=0; i<n; i++) System.out.println(a[i]); } public static void main(String args[]) { read();
  • 22. Department of CSE, JNNCE, Shimoga Page 16 Design and Analysis of AlgorithmsLaboratory (15CSL47) System.out.println("Input Array"); display(); long start = System.nanoTime(); quicksort(0,n-1); long end = System.nanoTime(); long diff = end-start; System.out.println("Sorted Array"); display(); System.out.println("nTime in nanosecs : " + diff); } } Output: Run the program by varying Number of elements for Best Case, Worst Case and Average Cases and note down the time take for execution. Plot the graph of N vs Time Taken for each Case. N Best Case Worst Case Average Case
  • 23. Department of CSE, JNNCE, Shimoga Page 17 Design and Analysis of AlgorithmsLaboratory (15CSL47) 5. Sort a given set of n integer elements using Merge Sort method and compute its timecomplexity. 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. importjava.util.*; classmergeclass { staticinta[],b[]; staticintn; staticvoid merge(int low, int m, int h) { inti,j,k; i=low; j=m+1; k=low; while(i<=m && j <= h) { if(a[i] <= a[j]) { } else { } k++; } b[k]=a[i]; i++; b[k]=a[j]; j++; while(i<=m) { b[k]=a[i]; k++; i++; } while(j<=h) {
  • 24. Department of CSE, JNNCE, Shimoga Page 18 Design and Analysis of AlgorithmsLaboratory (15CSL47) b[k]=a[j]; j++; k++; } for(i=low; i<=h;i++) a[i]=b[i]; } staticvoidmergesort(int low, int h) { if(low<h) { int mid=(low+h)/2; mergesort(low,mid); mergesort(mid+1,h); merge(low,mid,h); } } staticvoid read() { Scanner s=newScanner(System.in); Random r = newRandom(); System.out.print("Enter value of n:"); n=s.nextInt(); a=newint[n]; b=newint[n]; for(inti=0;i<n;i++) { a[i]=r.nextInt(n); //random avg case input //a[i]=n-i; //reverse order input //a[i]=i; //sorted input //a[i]=s.nextInt(); //manual input } }
  • 25. Department of CSE, JNNCE, Shimoga Page 19 Design and Analysis of AlgorithmsLaboratory (15CSL47) staticvoid display() { for(inti=0;i<n;i++) System.out.println(a[i]); } publicstaticvoid main(String s[]) { read(); System.out.println("Input Array"); display(); long start=System.nanoTime(); mergesort(0,n-1); long end= System.nanoTime(); System.out.println("Sorted Array"); display(); long diff=end-start; System.out.println("Time in nano seconds:"+diff); } } Output: Run the program by varying Number of elements for Best Case, Worst Case and Average Cases and note down the time take for execution. Plot the graph of N vs Time Taken for each Case. N Best Case Worst Case Average Case
  • 26. Department of CSE, JNNCE, Shimoga Page 20 Design and Analysis of AlgorithmsLaboratory (15CSL47) 6. Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming method (b) Greedy method. importjava.util.*; classksack { staticintn,M,M1; staticintw[],p[]; staticintf[][]; staticvoiddysack() { f=newint[n+1][M+1]; //table for(inti=0;i<=n;i++) { for(int j=0;j<=M;j++) { if(i==0 || j==0) f[i][j]=0; elseif(w[i] > j) f[i][j] = f[i-1][j]; else } } f[i][j] = Math.max(f[i-1][j],f[i-1][j-w[i]]+p[i]); System.out.println("Solution Table of Dynamic Method"); for(inti=0;i<=n;i++) { for(int j=0;j<=M;j++) { System.out.print("t" + f[i][j]); } System.out.println(); } System.out.println("Solution with Dynamic Method is: " + f[n][M]); } staticvoiddyitems()
  • 27. Department of CSE, JNNCE, Shimoga Page 21 Design and Analysis of AlgorithmsLaboratory (15CSL47) { int sol[] = newint[n+1]; for(inti=n;i>0;i--) { if(f[i][M] != f[i-1][M]) { } else { } } sol[i] = 1; M = M-w[i]; sol[i] = 0; System.out.print("The solution vector is:"); for(inti=1;i<=n;i++) System.out.print(" "+sol[i]); } staticvoidgreedysack() { int sum=0; double ratio[]=newdouble[n+1]; int sol[] = newint[n+1]; for(inti=1;i<=n;i++) { ratio[i]=(double)p[i]/w[i]; //profit to weight ratio } for (int q=1;q<=n;q++) { double max=0.0; int k = 0; //to store max ratio index for(inti=1;i<=n;i++) { if( (ratio[i] > max) && (sol[i] == 0)) {
  • 28. Department of CSE, JNNCE, Shimoga Page 22 Design and Analysis of AlgorithmsLaboratory (15CSL47) max=ratio[i]; k = i; } } if(M1>= w[k]) { } else { } } sol[k] = 1; //selected M1 = M1 - w[k]; sum = sum + p[k]; sol[k] = -1; //cannot select for(inti=1;i<=n;i++) { if(sol[i] == -1) sol[i] = 0; } System.out.println("nSolution with Greedy Method: "+sum); System.out.print("The solution vector is:"); for(inti=1;i<=n;i++) System.out.print(" "+sol[i]); } staticvoid read() { Scanner s=newScanner(System.in); System.out.print("Enter num of items: "); n=s.nextInt(); w=newint[n+1]; //weight p=newint[n+1]; //profit System.out.print("Enter Knapsack size: "); M=s.nextInt(); M1=M;
  • 29. Department of CSE, JNNCE, Shimoga Page 23 Design and Analysis of AlgorithmsLaboratory (15CSL47) System.out.println("Enter Weights of all Items"); for(inti=1;i<=n;i++) { w[i]=s.nextInt(); } System.out.println("Enter Profits of all Items"); for(inti=1;i<=n;i++) { p[i]=s.nextInt(); } } publicstaticvoid main(String args[]) { read(); dysack(); dyitems(); greedysack(); } } Output-1: Knapsack Capacity = 6 Enter num of items: 5 Enter Knapsack size: 6 Enter Weights of all Items 3 2 1 4 5 Enter Profits of all Items 25 20 15 40 50 Solution Table of Dynamic Method 0 0 0 0 0 0 0 0 0 0 25 25 25 25
  • 30. Department of CSE, JNNCE, Shimoga Page 24 Design and Analysis of AlgorithmsLaboratory (15CSL47) 0 0 20 25 25 45 45 0 15 20 35 40 45 60 0 15 20 35 40 55 60 0 15 20 35 40 55 65 Solution with Dynamic Method is: 65 The solution vector is: 0 0 1 0 1 Solution with Greedy Method:60 The solution vector is: 1 1 1 0 0 Output-2: Knapsack Capacity =5 Enter num of items: 4 Enter Knapsack size: 5 Enter Weights of all Items 2 1 3 2 Enter Profits of all Items 12 10 20 15 Solution Table of Dynamic Method 0 0 0 0 0 0 0 0 12 12 12 12 0 10 12 22 22 22 0 10 12 22 30 32 0 10 15 25 30 37 Solution with Dynamic Method is:37 The solution vector is: 1 1 0 1 Solution with Greedy Method:37 The solution vector is: 1 1 0 1
  • 31. Department of CSE, JNNCE, Shimoga Page 25 Design and Analysis of AlgorithmsLaboratory (15CSL47) 7. From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm. Write the program in Java. importjava.util.*; classdij { staticintn,src; staticintc[][]; staticintvis[],dist[]; staticintcount; staticvoid read() { Scanner s=newScanner(System.in); System.out.print("Enter no of vertices:"); n=s.nextInt(); c=newint[n+1][n+1]; vis=newint[n+1]; dist=newint[n+1]; System.out.println("Enter cost matrix:"); for(inti=1;i<=n;i++) { for(int j=1;j<=n;j++) { c[i][j]=s.nextInt(); } } System.out.print("Enter source node:"); src=s.nextInt(); } staticvoidsolvedijkstras() { int u=0,min; for(int j=1;j<=n;j++) { dist[j]=c[src][j]; } dist[src]=0;
  • 32. Department of CSE, JNNCE, Shimoga Page 26 Design and Analysis of AlgorithmsLaboratory (15CSL47) vis[src]=1; count=1; while(count!=n) { min=9999; for(int j=1;j<=n;j++) { if(dist[j]<min &&vis[j]!=1) { min=dist[j]; u=j; } } vis[u]=1; count++; for(int j=1;j<=n;j++) { if((min + c[u][j] <dist[j]) &&vis[j]!=1) { dist[j]=min+c[u][j]; } } } System.out.println("The shortest distance is:"); for(int j=1;j<=n;j++) { System.out.println(src+"--->"+j+" = "+dist[j]); } } publicstaticvoid main(String s[]) { read(); solvedijkstras(); } } Output:
  • 33. Department of CSE, JNNCE, Shimoga Page 27 Design and Analysis of AlgorithmsLaboratory (15CSL47) Enter no of vertices:5 Enter cost matrix: Enter source node:4 The shortest distance is: 4--->1 = 5 4--->2 = 2 4--->3 = 5 4--->4 = 0 4--->5 = 4 0 3 9999 7 9999 3 0 4 2 9999 9999 4 0 5 6 7 2 5 0 4 9999 9999 6 4 0
  • 34. Department of CSE, JNNCE, Shimoga Page 28 Design and Analysis of AlgorithmsLaboratory (15CSL47) 8. Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's algorithm. Use Union-Find algorithms in your program. importjava.util.*; classkruskal { staticintn; staticintc[][]; staticvoidsolvekruskal() { int u=0,v=0,a=0,b=0,min=0; int count=0,mincost=0; int parent[]=newint[n+1]; while(count != n+1) { min=9999; for(inti=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(c[i][j]<min && (i!=j)) { min=c[i][j]; u=a=i; v=b=j; } } } while(parent[u]!=0) { u=parent[u]; } while(parent[v]!=0) { v=parent[v]; } if(u!=v)
  • 35. Design and Analysis of AlgorithmsLaboratory (15CSL47) { System.out.println(a+"--->"+b +" = "+ min); parent[v]=u; mincost = mincost+min; } c[a][b]=c[b][a]=9999; count++; } System.out.println("mincost =" +mincost); } staticvoid read() { Scanner s=newScanner(System.in); System.out.print("Enter no. of vertices: "); n=s.nextInt(); c=newint[n+1][n+1]; System.out.println("Enter cost matrix:"); for(inti=1;i<=n;i++) { for(int j=1;j<=n;j++) { c[i][j]=s.nextInt(); } } } publicstaticvoid main(String s[]) { read(); System.out.println("The Spanning Tree is: "); solvekruskal(); } } Output: Enter no of vertices:5 Enter cost matrix: 0 3 9999 7 9999 3 0 4 2 9999 Department of CSE, JNNCE, Shimoga Page 29
  • 36. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 30 9999 4 0 5 6 7 2 5 0 4 9999 9999 6 4 0 The Spanning Tree is: 2--->4 = 2 1--->2 = 3 2--->3 = 4 4--->5 = 4 mincost =13
  • 37. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 31 9. Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's algorithm. importjava.util.*; class prim { staticintn; staticintc[][]; staticvoidsolveprims() { int u=0,v=0,min=0; int ne=0, mincost=0; intelec[]=newint[n+1]; elec[1]=1; while(ne != n-1) { min=9999; for(inti=1;i<=n;i++) { for(intj=1;j<=n;j++) { if(elec[i]==1) { if(c[i][j]<min) { min=c[i][j]; u=i; v=j; } } } } if(elec[v]!=1) { System.out.println(u+"--->"+ v + " = " +min); elec[v] = 1; ne = ne+1;
  • 38. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 32 mincost = mincost+min; } c[u][v] = c[v][u] = 9999; } System.out.println("nmincost = "+mincost); } staticvoid read() { Scanner s=newScanner(System.in); System.out.print("Enter no. of vertices:"); n=s.nextInt(); c=newint[n+1][n+1]; System.out.println("Enter the cost matrix:"); for(inti=1;i<=n;i++) { for(int j=1;j<=n;j++) { c[i][j] = s.nextInt(); } } } publicstaticvoid main(String s[]) { read(); System.out.println("The Spanning Tree is: "); solveprims(); } } Output: Enter no of vertices:5 Enter cost matrix: 0 3 9999 7 9999 3 0 4 2 9999 9999 4 0 5 6 7 2 5 0 4
  • 39. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 33 9999 9999 6 4 0 The Spanning Tree is: 1--->2 = 3 2--->4 = 2 2--->3 = 4 4--->5 = 4 mincost =13
  • 40. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 34 10. Write Java programs to (a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm. importjava.util.*; classfloyd { staticintn; staticintd[][]; staticvoidsolvefloyd() { for(int k=1;k<=n;k++) { for(inti=1;i<=n;i++) { for(int j=1;j<=n;j++) { d[i][j] = Math.min(d[i][j],d[i][k]+d[k][j]); } } } } staticvoid read() { Scanner s=newScanner(System.in); System.out.print("Enter no. of vertices :"); n=s.nextInt(); d=newint[n+1][n+1]; System.out.println("Enter the cost matrix:"); for(inti=1;i<=n;i++) { for(int j=1;j<=n;j++) { d[i][j]=s.nextInt(); } } } staticvoid display()
  • 41. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 35 0 3 9999 7 9999 3 0 4 2 9999 9999 4 0 5 6 7 2 5 0 4 9999 9999 6 4 0 { System.out.println("The least distance matrix is "); for(inti=1;i<=n;i++) { for(int j=1;j<=n;j++) { System.out.print(" "+d[i][j]); } System.out.println(); } } publicstaticvoid main(String s[]) { read(); solvefloyd(); display(); } } Output: Enter no. of vertices :5 Enter the cost matrix: The least distance matrix is 0 3 7 5 9 3 0 4 2 6 7 4 0 5 6 5 2 5 0 4 9 6 6 4 0
  • 42. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 36 10 (b) Implement Travelling Sales Person problem using Dynamic programming. importjava.util.*; class TSP { staticint n; staticint c[][]; static String path[]; staticintnumpath=0; static void findpath() { intminval = 9999; intminindex = 0; for(inti=0;i<numpath;i++) { intpathcost = 0; int pre = 1, k = 1; StringTokenizerst= new StringTokenizer(path[i],"->"); while(st.hasMoreTokens()) { k = Integer.parseInt(st.nextToken()); pathcost= pathcost + c[pre][k]; pre = k; } pathcost = pathcost+c[k][1]; if(pathcost<minval) { minval = pathcost; minindex = i; } } path[minindex] = path[minindex] + "->1"; System.out.println("TSP PATH is "+path[minindex]); } staticintsolveTSP(int k, int set[],String pathseq) {
  • 43. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 37 int count = 0, value = 0; int min = 999; for(intj=1;j<=n;j++) { if(set[j] == 1) count++; } if(count == 0) { } else { path[numpath++] = pathseq; return c[k][1]; for(inti=2; i<=n; i++) { if((i!=k) && (set[i]!=0)) { set[i] = 0; value = c[k][i] + solveTSP(i, set,pathseq+"->"+i); if(value < min) { min = value; } set[i] = 1; } } } return min; } static void read() { Scanner s=new Scanner(System.in); System.out.print("Enter no. of vertices: "); n=s.nextInt(); c = new int[n+1][n+1]; int size = (int) Math.pow(2, n);
  • 44. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 38 path = new String[size]; System.out.println("Enter cost matrix:"); for(inti=1;i<=n;i++) { for(int j=1;j<=n;j++) { c[i][j]=s.nextInt(); } } } public static void main(String s[]) { read(); int set[] = new int [n+1]; for(inti=1;i<=n;i++) set[i] = 1; set[1]=0; System.out.println("TSP Result is " + solveTSP(1,set,"1")); findpath(); } } Output: Enter no. of vertices: 5 Enter cost matrix: 0 2 0 6 1 1 0 4 4 2 5 3 0 1 5 4 7 2 0 1 2 6 3 6 0 TSP Result is 9 TSP PATH is 1->3->4->5->2->1 Enter no. of vertices: 4 Enter cost matrix: 0 10 15 20
  • 45. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 39 5 0 9 10 6 13 0 12 8 8 9 0 TSP Result is 35 TSP PATH is 1->2->4->3->1 Enter no. of vertices: 4 Enter cost matrix: 0 10 15 20 10 0 35 25 15 35 0 30 20 35 30 0 TSP Result is 80 TSP PATH is 1->2->4->3->1
  • 46. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 40 11. Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn} of n positive integers whose SUM is equal to a given positive integer d. For example, if S={1, 2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the given problem instance doesn't have a solution. importjava.util.*; class subset { staticintn, d, count; staticintset[], select[]; staticvoidsolvesubset(int m, int k, intsumr) { if(k >n+1) return; //m = partial sum of selected elements //k = index of element being processed, //sumr = sum of remaining elements of set select[k] = 1; if (m + set[k] == d) { //adding element k gives solution count++; System.out.println("nSolution " + count); for (inti = 1; i<= k; i++) { if (select[i] == 1) { System.out.print("t" + set[i]); } } } elseif (k+1 <= n) { //can element be added? if (m + set[k] + set[k+1] <= d) {
  • 47. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 41 solvesubset(m + set[k], k+1, sumr - set[k]); } } if (k+1 <= n) { if ((m + sumr - set[k] >= d) && (m + set[k+1] <= d)) { //try for solution without element k select[k] = 0; solvesubset(m, k+1, sumr - set[k]); } } } staticvoid read() { Scanner s = newScanner(System.in); System.out.print("Enter num of Elements :"); n=s.nextInt(); set = newint[n+1]; select =newint[n+1]; System.out.print("Enter the Elements:"); for(inti=1;i<=n;i++) { set[i]=s.nextInt(); } System.out.print("Enter Sum value :"); d = s.nextInt(); } publicstaticvoid main(String args[]) { intsumr = 0; read(); for(inti=1;i<=n;i++) {
  • 48. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 42 sumr = sumr + set[i]; } solvesubset(0, 1, sumr); if(count==0) System.out.println("No solution Exists"); } } Output: Enter num of Elements :6 Enter the Elements :2 4 6 8 10 12 Enter Sum value :10 Solution 1 2 8 Solution 2 4 6 Solution 3 10 Enter num of Elements :6 Enter the Elements : 2 4 6 8 10 12 Enter Sum value :17 No solution Exists Enter num of Elements :6 Enter the Elements : 2 4 6 8 10 12 Enter Sum value :28 Solution 1 2 4 10 12 Solution 2 2 6 8 12 Solution 3 4 6 8 10 Solution 4 6 10 12
  • 49. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 43 12. Design and implement in Java to find all Hamiltonian Cycles in a connected undirected Graph G of n vertices using backtracking principle. importjava.util.*; class ham { staticintn, start; staticintG[][]; staticintx[]; staticbooleanfound = false; staticvoid read() { Scanner s = newScanner(System.in); System.out.print("Enter the Num of Nodes: "); n = s.nextInt(); G = newint[n+1][n+1]; x = newint[n+1]; System.out.println("Enter the Adjacency Matrix: "); for(inti=1;i<=n;i++) { for(int j=1;j<=n;j++) { G[i][j]=s.nextInt(); } } System.out.print("Enter the Starting Node :"); start = s.nextInt(); } staticvoidnextvalue(intk) { int j=0; do { x[k]=(x[k]+1)%(n+1); if(x[k]==0)
  • 50. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 44 return; if(G[x[k-1]][x[k]]==1) { for( j=1;j<=k-1;j++) if(x[j]==x[k]) break; } }while(true); } if(j==k) if(k<n || ((k==n) &&G[x[n]][x[1]]==1)) return; staticvoidhamilton(int k) { x[1] = start; do{ nextvalue(k); if(x[k] == 0) return; if(k==n) { } else } found = true; System.out.println("Hamilton Cycle Path is"); for(inti=1;i<=n;i++) System.out.print(x[i] + " -->"); System.out.println(" "+start); hamilton(k+1); while(true); } publicstaticvoid main(String args[]) {
  • 51. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 45 read(); hamilton(2); if(!found) System.out.print("Hamilton Cycle doesnot Exists"); } } Output 1: Enter the Num of Nodes: 8 Enter the Adjacency Matrix: Enter the Starting Node:1 Hamilton Cycle Path is 1-->2-->8-->7-->6-->5-->4-->3-->1 Hamilton Cycle Path is 1-->3-->4-->5-->6-->7-->8-->2-->1 Output 2: Enter the Num of Nodes: 8 Enter the Adjacency Matrix: Enter the Starting Node:4 Hamilton Cycle Path is 4-->3-->1-->2-->8-->7-->6-->5-->4 0 1 1 0 0 0 1 0 1 0 1 0 0 0 0 1 1 1 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 1 0 0 0 0 1 0 0 1 1 0 0 0 1 0 1 0 1 0 0 0 0 1 1 1 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 1 0 0 0 0 1 0
  • 52. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 46 Hamilton Cycle Path is 4-->5-->6-->7-->8-->2-->1-->3-->4 Output 3: Enter the Num of Nodes: 5 Enter the Adjacency Matrix: Enter the Starting Node:2 Hamilton Cycle doesnot Exists 0 1 0 0 1 1 0 1 1 1 0 1 0 1 0 0 1 1 0 0 1 1 0 0 0
  • 53. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 47 Viva Questions 1) What is the time complexity of linear search? Θ(n) 2) What is the time complexity of binary search? Θ(log2n) 3) What is the major requirement for binary search? The given list should be sorted. 4) What is binary search? It is an efficient method of finding out a required item from a given list, provided the list is in order. The process is: 1. First the middle item of the sorted list isfound. 2. Compare the item with thiselement. 3. If they are equal search is complete. 4. If the middle element is greater than the item being searched, this process is repeated in the upper half of the list. 5. If the middle element is lesser than the item being searched, this process is repeated in the lower half of the list. 5) What is parental dominance? The key at each node is greater than or equal to the keys at its children. 6) What is heap? A heap can be defined as a binary tree with keys assigned to its nodes ( one key per node) provided the following two conditions are met:
  • 54. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 48 1 The tree’s shape requirement – The binary tree is essentially complete ( or simply complete), that is, all its levels are full except possibly the last level, where only some rightmost leaves may be missing. 2. The parental dominance requirement – The key at each node is greater than or equal to the keys at its children. 7) What is height of Binary tree? It is the longest path from the root to any leaf. 8) What is the time complexity of heap sort? Θ( n logn) 9) What is Merge Sort? Merge sort is an O (n log n) comparison-based sorting algorithm. Where the given array is divided into two equal parts. The left part of the array as well as the right part of the array is sorted recursively. Later, both the left part and right part are merged into a single sorted array. 10) Who invented Merge Sort? John Von Neumann in 1945. 11) On which paradigm is it based? Merge-sort is based on the divide-and-conquer paradigm. 12) What is the time complexity of merge sort? n log n. 13) What is the space requirement of merge sort? Space requirement: Θ(n) (not in-place). 14) When do you say an algorithm is stable and inplace? Stable – if it retains the relative ordering. In – place if it does not use extra memory. 15 ) Name the design strategy used in Selection Sort. Brute force
  • 55. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 49 16) Define Brute force strategy. Brute force is a straight forward approach to solving a problem, usually directly based on the problem’s statement and definitions of the concepts involved. 17) What is the time complexity of Selection Sort algorithm? (n2 ) 18) Is Selection Sort Inplace? Yes. 19) Is Selection Sort stable? Yes. 20) Why is the name Selection Sort? Algorithm selects the smallest number in the array and places it in its final position the sorted array. 21) When is Selection Sort algorithm useful? Selection Sort algorithm is useful for small inputs because it requires (n2 ) comparisons. Selection Sort algorithm requires (n-1) swaps & hence (n) memory writes. Thus it can be very useful if writes are the most expensive operation. 22) What are the drawbacks of Selection Sort? Inefficient on large lists. It requires same number of iterations no matter how well-organized the array is. It uses internal sorting, means it would require the entire array to be in main memory. 23) When is a problem said to have overlapping sub problems? A problem is said to have overlapping subproblems if it can be broken down into subproblems which are reused multiple times. This is closely related to recursion. 24) What is principle of optimality?
  • 56. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 50 The optimal solution to any instance of an optimization problem is composed of optimal solutions to its sub instances. 25) Can knapsack problem be solved in any other technique? It can be solved using many other techniques such as BruteForce, Greedy technique, Branch and bound etc.. 26) Mention few applications of dynamic programming. Can be applied to find factorial, fibonacci numbers in which the required value may depend on previously computed values. To find the longest common substrings of the strings "ABAB", "BABA" and "ABBA" are the strings "AB" and "BA" of length 2. Other common substrings are "A", "B" and the empty string “”. etc.. 27) Compare Dynamic programming and Divide and conquer. Dynamic programming differs from the "Divide and Conquer" (D-and-C) method in the fact that the problems solved by D-and-C can have many non- overlapping subproblems - i.e, new subproblems may be generated when the method is applied. Both use recursion. 28) Who invented Dijkstra’s Algorithm? Edsger Dijkstra invented this algorithm. 29) What is the other name for Dijkstra’s Algorithm? Single Source Shortest Path Algorithm. 30) Which technique the Dijkstra’s algorithm is based on? Greedy Technique. 31) What is the purpose of Dijkstra’s Algorithm? To find the shortest path from source vertex to all other remaining vertices 32) Name the different algorithms based on Greedy technique. Prim’s Algorithm, Kruskal’s algorithm 33) What is the constraint on Dijkstra’s Algorithm? This algorithm is applicable to graphs with non-negative weights only. 34) What is a Weighted Graph?
  • 57. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 51 A weighted graph is a graph with numbers assigned to its edges. These numbers are called weights or costs. 35) What is a Connected Graph? A graph is said to be connected if for every pair of its vertices u and v there is a path from u to v. 36) What is the time complexity of Dijkstra’s algorithm? For adjacency matrix, It is O(IVI*IVI) For adjacency list with edges stored as min heap, it is O(IEIlogIVI) 37) Differentiate b/w Traveling Salesman Problem(TSP) and Dijkstra’s Algorithm. In TSP, given n cities with known distances b/w each pair , find the shortest tour that passes through all the cities exactly once before returning to the starting city. In Dijkstra’s Algorithm, find the shortest path from source vertex to all other remaining vertices 38) Differentiate b/w Prim’s Algorithm and Dijkstra’s Algorithm? Prim’s algorithm is to find minimum cost spanning tree. Dijkstra’s algorithm is to find the shortest path from source vertex to all other remaining vertices. 39) What are the applications of Dijkstra’s Algorithm? It finds its application even in our day to day life while travelling. They are helpful in routing applications. 40) Who was the inventor of the Quicksort? C.A.R.HOARE, a British Scientist. 41) Which design strategy does Quicksort uses? Divide and Conquer 42) What is Divide and Conquer Technique? (I) Divide the instance of a problem into two or more smallerinstances (II) Solve the smaller instances recursively
  • 58. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 52 (III) Obtain solution to original instances by combining these solutions 43) What is the another name for Quicksort? Partition Exchange Sort 44) What are the advantages and disadvantages? Advantage: Fastest among all sorting algorithms Suitable when the input size is very large Disadvantage: Heavily based on recursive sorting technique It takes O (n* log n) time and O (log n) additional space due to Recursion 45) Is Quicksort Stable as well as In place? Not Stable but In place. 46) When do you say that a Quick sort having best case complexity? When the pivot exactly divides the array into equal half 47) When do you say that Quick sort having worst case complexity? When any one of the subarray is empty 48) How many more comparisons are needed for average case compared to best case? 38% more 49) when do you say that the pivot element is in its final position? When all the elements towards the left of pivot are <= pivot and all the elements towards the right of pivot are >= pivot. 50) What is CLK_TCK? macro defines the number of clock ticks per second which is available in the TIME.H header file. 51) What technique does kruskal’s algorithm follow. greedy technique
  • 59. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 53 52) What is the time complexity. With an efficient sorting algorithm, the time efficiency of an kruskal’s algorithm will be in O(|E|log|E|). 53) Who is the inventor of kruskal’s algorithm. Joseph Kruskal. 54) Which technique is used to solve BFS & DFS problems? Decrease and Conquer 55) What is BFS traversal? It proceeds in a concentric manner by visiting first all the vertices that are adjacent to a starting vertex, then all unvisited vertices two edges apart from it and so on , until all the vertices are in the same connected component as the starting vertex are visited. If there still remains unvisited vertices, the algorithm to be restarted at an arbitrary vertex of another connected component of a graph. 56) What is DFS traversal? Consider an arbitrary vertex v and mark it as visited on each iteration, proceed to an unvisited vertex w adjacent to v. we can explore this new vertex depending upon its adjacent information. This process continues until dead end is encountered.(no adjacent unvisited vertex is available). At the dead end the algorithm backs up by one edge and continues the process of visiting unvisited vertices. This process continues until we reach the starting vertex. 57) What are Tree edge, Back edge & Cross edge ? Tree edge: whenever a new unvisited vertex is reached for the first time, it is attached as a child to the vertex from which it is being visited. Such an edge is called a tree edge. Back edge: An edge leading to a previously visited vertex other than its immediate predecessor. Such an edge is called a back edge Cross edge If an edge leading to a previously visited vertex other than its immediate predecessor (i.e. its parent in the tree). Is encountered, the edge is noted as a cross edge. 58) What are the various applications of BFS & DFS tree traversal technique?
  • 60. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 54 Application of BFS Checking connectivity and checking acyclicity of a graph. Check whether there is only one root in the BFS forest or not. If there is only one root in the BFS forest, then it is connected graph otherwise disconnected graph. For checking cycle presence, we can take advantage of the graph's representation in the form of a BFS forest, if the latter vertex does not have cross edge, then the graph is acyclic. Application of DFS To check whether given graph is connected or not. To check whether the graph is cyclic or not. To find the spanning tree. Topological sorting. 59) Which data structures are used in BFS & DFS tree traversal technique? We use Stack data structure to traverse the graph in DFS traversal. We use queue data structure to traverse the graph in DFS traversal. 60) What are the efficiencies of BFS & DFS algorithms for Adjacency matrix and adjacency list representation? Adjacency matrices: Θ(V2 ) Adjacency linked lists: Θ(V+E) 61) Define set? Set is unordered collection of distinct items. 62) Define power set? The set of all subsets of a set is a power set. 63) Define squashed order? Any subsets involving aj can be listed only after all the subsets involving a1,…,aj-1(j=1,2,…,n-1)
  • 61. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 55 64) What are the ways of generating subsets? Decrease by constant Bit string based algorithm Minimal change algorithm 65) Explain time and space trade off strategy. It is a strategy in which time efficiency can be achieved at the cost of extra memory usage. 66) Which technique does the Horspool algorithm uses? Input enhancement technique 67) Explain Input enhancement technique. It is a technique in which the problem’s input is preprocessed in whole or in part and the additional information stored is obtained to solve the problem. 68) What is a shift table? It is a table that stores the shift information i.e it stores the distance of each rightmost character in the first “m-1” characters of the pattern from the last character of the pattern and stores the length of the pattern as the shift size if the character is not present in the pattern. 69) Which is better Brute Force or Horspool algorithm for string matching? Horspool is better as it reduces the number of comparisons. 70) Differentiate between Brute-Force technique and Horspool algorithm for string matching. a) In brute-force, comparison starts from left where as in Horspool comparison starts from right. b) In brute-force technique, if there is a character mismatch then we shift the pattern to the right by 1 position. In Horspool, if there is a mismatch then the shift size is obtained from the shift table and the pattern is shifted accordingly. 71) Differentiate between Horspool and Boyer -Moore algorithms. Horspool algorithm uses only Shift table to obtain the shift information.
  • 62. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 56 Boyer - Moore algorithm uses 2 tables. -Bad symbol shift table (same as the shift table used by Horspool).The shift information of this table is known as d1 -Good suffix shift table The shift information from this table is known as d2. Shifting is done by taking max(d1,d2). 72) What is Dynamic Programming? It is a technique for solving problems with overlapping sub problems. 73) What does Dynamic Programming have in common with Divide- and-Conquer? Both solve the problems by dividing the problem into sub problems. Using the solutions of sub problems, the solutions for larger instance of the problem can be obtained. 74) What is the Space & Time complexity of DP algo for Binomial Coefficient C(n, k)? Θ(nk) 75) What is a principle difference between the two techniques? Only one instance of the sub problem is computed & stored. If the same instance of sub problem is encountered, the solution is retrieved from the table and never recomputed. Very precisely re - computations are not preformed. 76) What is a spanning tree ? A spanning tree of a weighted connected graph is its connected acyclic(no cycles) subgraph (i.e. a tree)that contains all the vertices of a graph. 77) What is a minimum spanning tree ? Minimum spanning tree of a connected graph is its spanning tree of smallest weight. 78) Prim’s algorithm is based on which technique. Greedy technique.
  • 63. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 57 79) State greedy technique for solving problem. A greedy approach constructs a problem through a sequence of steps each expanding a partially constructed solution obtained so far, untill the complete solution is reached. On each step the choice must be made as Feasible: i.e. it has to satisfy the problem’s constraints. Locally optimal: i.e. it has to be the best local choice among all feasible choices available on that step. Irrevocable: i.e. once made, it cannot be changed on subsequent steps of the algorithm. What are fringes and unseen vertices? Fringes: vertices which are connected are called fringes. Unseen vertices : vertices which are not adjacent are called unseen. 80) Name some of the application greedy technique They are helpful in routing applications: In the case of network where large number of computers are connected, to pass the data from one node to another node we can find the shortest distance easily by this algorithm. Communication Networks: Suppose there are 5 different cities and we want to establish computer connectivity among them, then we take into the account of cost factor for communication links. Building a road network that joins n cities with minimum cost. 81) Does Prim’s Algorithm always yield a minimum spanning tree ? Yes 82) What is the purose of Floyd’s algoreithm? - To find the all pair shortestpath. 83) What is the time efficiency of floyd’s algorithm? - It is same as warshall’s algorithm that isθ(n3 ).
  • 64. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 58 84) What is distance matrix? - In which the element dij indicates the length of the path from ith vertex to the jth vertex. 85) What is shortest path? - It is the path which is having shortest length among all possiblepaths. 86) warshall’s algorithm is optimization problem or non-optimization problem ? Non-optimization problem 87) For what purpose we use Warshall’s algorithm? Warshall’s algorithm for computing the transitive closure of a directed graph 88) Warshall’s algorithm depends on which property? Transitive property 89) what is the time complexity of Warshall’s algorithm? Time complexity of warshall’s 90) what is hard problem? Optimization problems which are having complexity of exponential or factorial. 91) hard problems can be solved by which method? Back tracking and branch and bound techniques used for large instance of combinatorial problems. 92) what is state space tree? Constructing a tree of choices being made and processing is known as state-space- tree. Root represents an initial state before the search for solution begins. 93) what are promising and non-promising state-space-tree? Node which may leads to solution is called promising. Node which doesn’t leads to solution is called non-promising. (n3)
  • 65. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 59 94) Differentiate between backtracking and Branch and Bound. Branch and Bound uses Best first search technique and is applicable to optimization problems. Backtracking is applicable to non-optimization problems most of the times and sometimes optimization problems. It uses DFS search technique. 95) In Backtracking what does the leaf node indicates? It indicates either a non promising dead ends or solutions to the problem.
  • 66. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 60 Additional Problem (Dynamic Programming & Greedy Algorithms) I. Implement the job sequencing with deadlines problem using the fixed tuple size formulation. II. (a) (b) Implement the algorithm to compute roots of optimal sub-trees. Implement the optimal binary search tree problem.
  • 67. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 61 Additional Problem ( Greedy Algorithms) III.(a) Write an algorithm for partitioning problem. Partition problem is to determine whether a given set can be partitioned into two subsets such that the sum of elements in both subsets is same. (b) Find a subset of a given set S = {S1, S2, , Sm} 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}. A suitable message is to be displayed if the given problem instance doesn't have a solution. (c) Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = {S1, S2,..... , Sm} valued coins, how many ways can we make the change? The order of coins doesn‟t matter. For example, for N = 4 and S = {1, 2, 3}, there are four solutions: {1, 1, 1, 1}, {1, 1, 2}, {2, 2}, {1, 3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2, 2, 2, 2, 2}, {2, 2, 3, 3}, {2, 2, 6}, {2, 3, 5} and {5, 5}. So the output should be 5.
  • 68. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 62 Additional Problem (Graph Algorithms) I. Perform the following operations on Disjoint set: a) MAKE-SET b) UNION c) FIND-SET d) INSERT e) DELETE f) SPLIT g) Returns the minimum object in SET II. Perform the following Union-by-Weight operations on a universe of 10 elements (0-9, each initially in their own set). Draw the forest of trees that result. U(1,5); U(3,7); U(1,4);U(5,7); U(0,8); U(6,9); U(3,9). If the sets have equal weight, use the root with the smaller value as the root of the new set. III. Let G be a connected graph of order n. Write an algorithm for finding maximum number of Cut•vertices that G can contain. Cut•vertex is a vertex which when removed from the graph splits it into two disconnected components. IV. An Euler circuit for an undirected graph is a path that starts and ends at the same vertex and uses each edge exactly once. A connected undirected graph G has an Euler circuit. If and only If energy vertex is of even degree. Give an algorithm and implement to find the Euler Circuit in a graph with e edges provided one exists.
  • 69. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 63 Additional Problem (Other Techniques) I. Implement N Queen's problem. II. Implement Sudoku problem. III. Design an efficient solution for tower of Hanoi problem. IV. Implement 0/1 Knapsack problem. V Implement the travelling salesman problem (TSP). VI. Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6) Length | 1 2 3 4 5 6 7 8 ---------------------------------------------------- - Price | 1 5 8 9 10 17 17 20 VII Implement the Coin change problem. VIII. Design the Graph coloring problem
  • 70. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 64 MULTIPLE CHOICE QUESTIONS 1. You have to sort a list L consistnn of a sorted list followed by a few random el- ements. Which of the followinn sortnn methods would be especially suitable for such a task? A) Bubble sort B) Selecton sort C) Quick sort D) Inserton sort 2. A technique for direct search is ....................................... A) Binary Search B) Linear Search C) Tree Search D) Hashinn 3. The searchinn technique that takes O(1) tme to fnd a data is (A) Linear Search (B) Binary Search (C) Hashinn (D) Tree Search 4. The number of interchannes required to sort 5, 1, 6, 2 4 in ascendinn order usinn Bubble Sort is (A) 6 (B) 5 (C) 7 (D) 8 5. The postix form of the expression (A + B) ∗ (C ∗ D − E) ∗ F/G is (A) AB + CD ∗ E − FG/ ∗ ∗ (B) AB + CD ∗ E − F ∗ ∗G/ (C) AB + CD ∗ E − ∗F ∗ G/ (D) AB + CDE ∗ − ∗ F ∗ G/ 6. The complexity of multplyinn two matrices of order m*n and n*p is (A) mnp (B) mp (C) mn (D) np
  • 71. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 65 7. In worst case Quick Sort has order (A) O (n lon n) (B) O (lon n) (C) O (n 2 /2) (D) O (n 2/4) 8. A full binary tree with 2n+1 nodes contain (A) n leaf nodes (B) n non-leaf nodes (C) n-1 leaf nodes (D) n-1 non-leaf nodes 9. A linear list of elements in which deleton can be done from one end (front) and inserton can take place only at the other end (rear) is known asa (A) queue. (B) stack. (C) tree. (D) linked list. 10. A sort which relatvely passes throunh a list to exchanne the frst element with any element less than it and thenrepeats with a new frst element is called (A) inserton sort. (B) selecton sort. (C) heap sort. (D) quick sort. 11. Which of the followinn sortnn alnorithms does not have a worst case runninn tme of O(n 2 ) ? (A) Inserton sort (B) Merne sort (C) Quick sort (D) Bubble sort 12. Consider a linked list of n elements. What is the tme taken to insert an element after an element pointed by some pointer? (A) O (1) (B) O ( lon 2 n ) (C) O (n) (D) O ( n lon 2 n ) 13. The data structure required for Breadth First Traversal on a nraph is (A) queue (B) stack
  • 72. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 66 (C) array (D) tree 14. In a circular linked list (A) components are all linked tonether in some sequentalmanner. (B) there is no beninninn and no end. (C) components are arranned hierarchically. (D) forward and backward traversal within the list is permited. 15. The quick sort alnorithm exploit ————– desinn technique (A) Greedy (B) Dynamic pronramminn (C) Divide and Conquer (D) Backtracking 16. The number of diferent directed trees with 3 nodes are (A) 2 (B) 3 (C) 4 (D) 5 17. The data structure required to evaluate a postix expression is (A) queue (B) stack (C) array (D) linked-list 18. The data structure required to check whether an expression contains balanced parenthesis is (A) Stack (B) Queue (C) Tree (D) Array 19. The complexity of searchinn an element from a set of n elements usinn Binary search alnorithm is (A) O(n) (B) O(lon n) (C) O(n 2 ) (D) O(n lon n)
  • 73. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 67 20. What data structure would you mostly likely see in a nonrecursive implementaton ofa recursive alnorithm? (A) Stack (B) Linked list (C) Queue (D) Trees Which of the followinn sortnn methods would be most suitable for sortnn a list which is almost sorted ? (A) Bubble Sort (B) Inserton Sort (C) Selecton Sort (D) Quick Sort 22. A binary tree of depth ”d” is an almost complete binary tree if (A) Each leaf in the tree is either at level ”d” or at level”d-1” (B) For any node ”n” in the tree with a rinht descendent at level ”d” all theleft descendent of ”n” that are leaves, are also at level ”d” (C) Both (A) & (B) (D) None of the above 23. If the address of A[1][1] and A[2][1] are 1000 and 1010 respectvely and each ele- ment occupies 2 bytes then the array has been stored in —————order. (A) row major (B) column major (C) matrix major (D) none of these 24. An adjacency matrix representaton of a nraph cannot contain informaton of : (A) nodes (B) ednes (C) directon of ednes (D) parallel ednes 25. O(N) (linear tme) is beter than O(1) constant tme. (A) True (B) False
  • 74. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 68 26. The best averane behaviour is shown by (A) Quick Sort (B) Merne Sort (C) Inserton Sort (D) Heap Sort 27. A queue is a, (A) FIFO (First In First Out) list. (C) Ordered array. (B) LIFO (Last In First Out) list. (D) Linear tree. 28. Which data structure is needed to convert infx notaton to postixnotaton? (A) Branch (B) Queue (C) Tree (D) Stack 29. Consider that n elements are to be sorted. What is the worst case tme complexity of Bubble sort? (A) O(1) (C) O(n) (B) O(lon 2 n) (D) O(n 2 ) 30. A characteristc of the data that binary search uses but the linear search innores is the ——————-. (A) Order of the elements of thelist. (B) Lennth of the list. (C) Maximum value in list. (D) Type of elements of the list. 31. In Breadth First Search of Graph, which of the followinn data structure is used? (A) Stack. (B) Queue. (C) Linked List. (D) None of the above. 32. In order to net the contents of a Binary search tree in ascendinn order, one has to traverse it in
  • 75. Design and Analysis of AlgorithmsLaboratory (15CSL47) Department of CSE, JNNCE, Shimoga Page 69 (A) pre-order. (B) in-order. (C) post order. (D) not possible. 33. In binary search, averane number of comparison required for searchinn an element in a list if n numbers is (A) lon 2 n . (B) n / 2 . (C) n. (D) n - 1. 34. The worst case of quick sort has order (A) O(n 2 ) (B) O(n) (C) O (n lon 2 n) (D) O (lon 2 n) 35. The tme required to delete a node x from a doubly linked list havinn n nodes is (A) O (n) (B) O (lon n) (C) O (1) (D) O (n lon n)