Daa Lab Manual (18csl47) 2020-21
Daa Lab Manual (18csl47) 2020-21
DESIGN AND ANALYSIS OF ALGORITHM LABORATORY [As per Choice Based Credit
System (CBCS) scheme] (Effective from the academic year 2018 -2019) SEMESTER –
IV
Subject Code 18CSL47 IA Marks 40
Number of Lecture Hours/Week 02 I + 02 P Exam Marks 60
Total Number of Lecture Hours 36 Exam Hours 03
CREDITS – 02
Description
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.
Experiments
1 (a) Create a Java class called Student with the following details as variables within it.
(i) USN (ii) Name (iii) Branch (iv) Phone
Write a Java program to create n Student objects and print the USN, Name, Branch, and
Phone of these objects with suitable headings.
(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 super class called Staff with details as StaffId, Name, Phone, Salary. Extend
this class by writing three subclasses namely Teaching (domain, publications), Technical
(skills), and Contract (period). Write a Java program to read and display at least 3 staff
objects of all three categories.
(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 String Tokenizer 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 hashtree
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.
4 Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n > 5000 and record the time taken to
sort. Plot a graph of the time taken versus n on graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using Java
how the divide and conquer method works along with its time complexity analysis: worst
case, average case and best case.
5 Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program for varied values of n > 5000, and record the time taken to
sort. Plot a graph of the time taken versus n on graph sheet. The elements can be read from
a file or can be generated using the random number generator. Demonstrate using Java
how the divide and conquer method works along with its time complexity analysis: worst
case, average case and best case.
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 connected undirected graph using Prim's
algorithm.
11 Design and implement in Java to find a subset of a given set S = {S1, S2, ….. Sn} of n
positive integers whose SUM is equal to a given positive integer d. 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.
Program - 1. a) Create a Java class called Student with the following details as
variables within it. (i) USN (ii) Name (iii) Branch (iv) Phone
Write a Java program to create n Student objects and print the USN, Name, Branch,
and Phone of these objects with suitable headings.
import java.io.*;
import java.util.Scanner;
class Student
{
String usn, name, branch;
long phone;
Student (String u, String n, String b, long p)
{
usn=u;
name=n;
branch=b;
phone=p;
}
void display ( )
{
System.out.println( );
System.out.println("USN: "+usn);
System.out.println("NAME: "+name);
System.out.println("BRANCH: "+branch);
System.out.println("PHONE: "+phone);
}
System.out.println("Student Details");
for (i=0; i<n; i++)
s[i].display ( );
}
}
Output:
Program – 1 b) Write a Java program to implement the Stack using arrays. Write
Push (), Pop (), and Display () methods to demonstrate its working.
import java.io.*;
import java.util.Scanner;
class Stack
{
private int maxsize, top;
private int stack[ ];
Output:
Program – 2 a) Design a super class called Staff with details as StaffId, Name, Phone,
and Salary. Extend this class by writing three subclasses namely Teaching (domain,
publications), Technical (skills), and Contract (period). Write a Java program to read
and display at least 3 staff objects of all three categories.
import java.io.*;
class Staff
{
private int StaffId;
private String Name;
private String Phone;
private long Salary;
public Staff(int staffId,String name,String phone,long salary)
{
StaffId = staffId;
Name = name;
Phone = phone;
Salary = salary;
}
public void Display()
{
System.out.print(StaffId+"\t"+Name+"\t"+Phone+"\t"+Salary);
}
}
class Teaching extends Staff
{
private String Domain;
private int Publications;
public Teaching(int staffId, String name, String phone, long salary, String domain,
int publications)
{
super(staffId, name, phone, salary);
Domain = domain;
Publications = publications;
}
public void Display()
{
super.Display();
System.out.print("\t"+Domain+"\t"+Publications+"\t\t-\t-");
}
}
class Technical extends Staff
{
private String Skills;
public Technical(int staffId, String name, String phone, long salary, String skills)
{
super(staffId, name, phone, salary);
Skills = skills;
}
public void Display()
{
super.Display();
System.out.print("\t-\t-\t"+Skills+"\t-");
}
}
class Contract extends Staff
{
private int Period;
public Contract(int staffId, String name, String phone, long salary, int period)
{
super(staffId, name, phone, salary);
this.Period = period;
}
public void Display()
{
super.Display();
System.out.print("\t-\t-\t-\t-\t"+Period);
}
}
public class Lab2A
{
public static void main(String[] args)
{
Staff staff[]=new Staff[3];
staff[0]=new Teaching(1,"Nagesh","271173",90000,"CSE",3);
staff[1]=new Technical(2,"Tara","271172",2000,"Server
Admin"); staff[2]=new Contract(3,"Rahul","271174",9000,3);
System.out.println("StaffID\tName\tPhone\tSalary\tDomain\tPublication\tSkills\t
Period");
for(int i=0;i<3;i++)
{
staff[i].Display();
System.out.println();
}
}
}
Output:
Program – 2 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 String Tokenizer class considering the delimiter character as “/”.
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
class Customer
{
String temp;
String dd, mm, yyyy;
public void rd(String n, String d)
{
StringTokenizer token = new StringTokenizer (d, "/");
dd = token.nextToken ( );
mm = token.nextToken ( );
yyyy = token.nextToken ( );
System.out.println (n +"\t"+dd+","+mm+","+yyyy);
}
Output:
Program – 3 a) Write a Java program to read two integers a and b. Compute a/b and
print, when b is not zero. Raise an exception when b is equal to zero.
import java.io.*;
import java.util.Scanner;
class Integer
{
public static void main(String args[])
{
int a, b, res;
Scanner in = new Scanner(System.in);
System.out.println("Enter two numbers ");
a = in.nextInt ( );
b = in.nextInt ( );
try
{
res=a/b;
System.out.println("Result= "+res);
}
catch(ArithmeticException e)
{
System.out.println("Exception: Divide by zero error "+e);
}
}
}
Output:
import java.util.*;
class Num extends Thread
{
public void run()
{
int n=0;
Random r=new Random();
try
{
for(int i=0;i<5;i++)
{
n=r.nextInt(100);
System.out.println("First thread generated number is: +n);
Thread t2=new Thread (new SNum(n));
t2.start();
{
System.out.println("Third thread: Cube of the number is: "+x*x*x);
}
}
Output:
Program – 4 Sort a given set of n integer elements using Quick Sort method and
compute its time complexity. Run the program for varied values of n > 5000 and
record the time taken to sort. Plot a graph of the time taken versus n on graph sheet.
The elements can be read from a file or can be generated using the random number
generator. Demonstrate using Java how the divide and conquer method works along
with its time complexity analysis: worst case, average case and best case.
import java.io.*;
import java.util.Random;
import java.util.Scanner;
class QuickSort
{
static int max=5000;
void quicksort(int a[], int low, int high)
{
int s;
if(low<high) //To check for boundary condition
{
s=partition(a,low,high);
quicksort(a,low,s-1);
quicksort(a,s+1,high);
}
}
int partition(int a[], int low, int high)
{
int p, i, j, temp;
p=a[low];
i=low+1;
j=high;
while (low<high)
{
while (a[i]<=p &&i<high)
i++;
while (a[j]>p)
j--;
if (i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
{
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;
}
} //End While
return j;
} //End Partition
public static void main(String args[])
{
int a[], i, n;
Scanner sc =new Scanner(System.in);
System.out.println("Enter the Number of elements to be sorted");
n=sc.nextInt();
a= new int[max]; //initialize array with max size
Random generator=new Random();
Output:
Program – 5 Sort a given set of n integer elements using Merge Sort method and
compute its time complexity. Run the program for varied values of n > 5000, and
record the time taken to sort. Plot a graph of the time taken versus n on graph sheet.
The elements can be read from a file or can be generated using the random number
generator. Demonstrate using Java how the divide and conquer method works along
with its time complexity analysis: worst case, average case and best case.
import java.io.*;
import java.util.Scanner;
import java.util.Random;
class MergeSort
{
static int max=5000;
void mergesort (int a[], int low, int high)
{
int mid;
if (low<high)
{
mid = (low+high)/2;
mergesort (a, low, mid);
mergesort (a, mid+1, high);
merge (a, low, mid, high);
}
}
void merge (int a[], int low, int mid, int high)
{
int i, j, k, t[] = new int[max];
i=low; j=mid+1; k=low; t= new int[max]; while ((i<=mid)
&& (j<=high)) {
long startTime=System.nanoTime();
MergeSort m=new MergeSort();
m.mergesort(a,0,n-1);
long stopTime=System.nanoTime();
long elapseTime=(stopTime-startTime);
System.out.println();
System.out.println("Sorted array is");
for(i=0;i<n;i++)
System.out.print(a[i]+”\t”);
System.out.println();
System.out.println("Time taken to sort array is:"+elapseTime+"nano
seconds");
}
}
Output:
import java.util.Scanner;
}
}
private static int max(int i, int j)
{
if(i>j) return i;
else return j;
}
static void optimal(int m,int n,int w[],int v[][])
{
int i = n, j = m, item=0, x[]=new int[10];
while( i != 0 && j != 0)
{
if(v[i][j] != v[i-1][j])
{
x[i] = 1;
j = j-w[i];
}
i = i-1;
}
System.out.println("Optimal solution is :"+
v[n][m]); System.out.println("Selected items are: ");
for(i=1; i<= n;i++)
if(x[i] == 1)
{
System.out.print(i+" ");
item=1;
}
if(item == 0)
System.out.println("NIL\t Sorry ! No item can be placed in Knapsack");
System.out.println("\n********* *********************** *************");
}
}
Output:
b) Greedy method.
import java.util.Scanner;
for(i=1;i<=n;i++)
ratio[i]=p[i]/w[i];
System.out.println("Information about knapsack problem are");
displayinfo(n,w,p,ratio);
System.out.println("Capacity = "+m);
sortArray(n,ratio,w,p);
w[j]=w[j+1];
w[j+1]=temp;
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
Output:
Program – 7 For a given vertex in a weighted connected graph, find shortest paths to
other vertices using Dijkstra's algorithm. Write the program in Java.
import java.io.*;
import java.util.Scanner;
public class Dijkstra
{
public static void main(String[] args)
{
int i, j;
int dist[]=new int[10], visited[]=new int[10]; int
cost[][]=new int[10][10], path[]=new int[10]; Scanner in =
new Scanner(System.in); System.out.println("****
DIJKSTRA'S ALGORITHM ******");
System.out.println("Enter the number of nodes: ");
int n = in.nextInt();
System.out.println("Enter the cost matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cost[i][j] = in.nextInt();
System.out.println("The entered cost matrix is");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(cost[i][j]+"\t");
}
System.out.println();
}
System.out.println("Enter the source vertex: ");
int sv = in.nextInt();
dij(cost,dist,sv,n,path,visited);
printpath(sv,n,dist,path,visited );
System.out.println("\n********* *************** *********");
}
static void dij(int cost[][],int dist[],int sv,int n,int path[],int visited[])
{
int count = 2,min,v=0;
for(int i=1; i<=n; i++)
{
visited[i]=0;
dist[i] = cost[sv][i];
if(cost[sv][i] == 999)
path[i] = 0;
else
path[i] = sv;
}
visited[sv]=1;
while(count<=n)
{
min = 999;
Input Graph
Output:
import java.io.*;
import java.util.Scanner;
if(u != v)
{
System.out.print((ne++)+") Minimum edge is: ");
System.out.println("("+a+"-->"+b+") and its cost is: "+min);
mincost += min;
parent[v] = u;
}
cost[a][b] = cost[b][a] = 999;
}
return mincost;
}
}
Input Graph
Output
import java.io.*;
import java.util.Scanner;
class Prims
{
void prim(int n, int a[][])
{
int i, j, k, u, v;
int sum, min, source;
int p[]=new int[10];
int d[]=new int[10];
int s[]=new int[10];
int t[][]=new int[10][2];
min=9999;
source=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]!=0&&a[i][j]<=min)
{
min=a[i][j];
source=i;
}
}
}
for(i=0;i<n;i++)
{
d[i]=a[source][i];
p[i]=source;
s[i]=0;
}
s[source]=1;
sum=0; k=0;
for(i=1;i<n;i++)
{
min=9999;
u=-1;
for(j=0;j<n;j++)
{
if(s[j]==0)
{
if(d[j]<min)
{
min=d[j];
u=j;
}
}
}
if(u==-1)
return;
t[k][0]=u;
t[k][1]=p[u];
k++;
sum=sum+a[u][p[u]];
s[u]=1;
for(v=0;v<n;v++)
{
if(s[v]==0 && a[u][v]<d[v])
{
d[v]=a[u][v];
p[v]=u;
}
}
}
if(sum>=9999)
{
System.out.println("spanning tree does not exists\n");
}
else
{
System.out.println("The Spanning Tree Exists and Minimum
Spanning Tree is\n");
for(i=0;i<n-1;i++)
{
System.out.println(t[i][0]+"--->"+t[i][1]);
}
System.out.println("The cost of the Spanning Tree = "+sum);
}
}
public static void main(String args[])
{
int i,j,n;
Prims p = new Prims();
int cost[][] = new int[10][10];
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number of nodes");
n = sc.nextInt();
System.out.println("Enter the adjacency matrix");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cost[i][j]=sc.nextInt();
}
}
p.prim(n,cost);
}
}
Input Graph
Output:
import java.io.*;
import java.util.Scanner;
Input Graph
Output:
import java.io.*;
import java.util.Scanner;
Input Graph
Output:
Program – 11 Design and implement in Java to find a subset of a given set S = {S1, S2,
….. Sn} of n positive integers whose SUM is equal to a given positive integer d. For
example, if S = {1, 2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}.
Display a suitable message, if the given problem instance doesn't have a solution.
import java.io.*;
import java.util.Scanner;
Output:
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
{
for(int i=0; i<pathcount-1; i++)
if(path[i] == v)
return true;
return false;
}
public void display()
{
System.out.println("\nPath : ");
for(int i=0; i<=V; i++)
System.out.print(path[i%V] + " ");
System.out.println();
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
HamiltonianCycle hc = new
HamiltonianCycle(); System.out.println("Enter
the no of Vertices"); int V = sc.nextInt();
System.out.println("Enter the Cost Adjacency Matrix");
int graph[][] = new int [V][V]; for (int i=0; i<V; i++)
Output:
Viva Questions
1. What is Algorithm?
2. Name the design techniques.
3. Which is efficient Sorting technique?
4. Which sorting technique has the lowest worst case efficiency?
5. Which sorting technique is space efficient?
6. Which sorting technique is Time efficient?
7. Define order of growth.
8. How binary search is advantageous over linear search?
9. What is divide & conquer technique?
10. Give few problems which can be solved using divide & conquer technique.
11. What is dynamic programming?
12. Give few problems which can be solved using dynamic programming.
13. What is Back Tracking?
14. Define N-Queens problem.
15. What is Brute force Methodology?
16. What is Greedy Technique?
17. Give few problems which can be solved using Greedy Technique.
18. Which is the efficient method for finding MST?
19. What is MST?
20. What is DFS & BFS?
21. What is a heap?
22. What are P NP problems?
23. Which are the String Matching algorithms?
24. What is Transitive closure?
25. Define Knapsack problem.
26. Define topological sorting?
27. Which algorithm used for checking graph is connected or not?
28. What is Java?
29. List applications of Java?
30. What is the role of static keyword in main function?
31. Why Arrays.fill ( ) method is used?
32. What is constructor? Mention its types.
33. Why Java won’t support copy constructor?
34. Explain Travelling Salesperson problem?
35. What is Hamiltonian cycle?
36. Define Exceptions.
37. Define a Thread. Explain the role of a Thread.
38. What is a Class?
39. What is an Object?
40. What is Reference variable?