Design and Analysis of Algorithms Laboratory Manual-15CSL47 4 Semester CSE Department, CIT-Mandya Cbcs Scheme
Design and Analysis of Algorithms Laboratory Manual-15CSL47 4 Semester CSE Department, CIT-Mandya Cbcs Scheme
Laboratory Manual-15CSL47
4th Semester CSE Department,
CIT-Mandya
CBCS SCHEME
Prepared by,
Hemachander N, Sachith B K,
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
Phone of these objects with suitable headings.
import java.util.Scanner;
class student {
String USN;
String Name;
String Branch;
String Phone;
public static void main(String args[]){
}
System.out.println("The Student Details are as follows ");
for(int j=0;j<n;j++)
{
System.out.println("Details of student "+(j+1)+" is");
System.out.println("Usn is "+students[j].USN);
System.out.println("Name is "+students[j].Name);
System.out.println("Branch is "+students[j].Branch);
System.out.println("Phone Number is "+students[j].Phone);
}
}
}
1. (B) Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display()
methods to demonstrate its working.
import java.util.Scanner;
public class StackDemo {
private int STACK_SIZE = 5;
int arr[] = new int[STACK_SIZE];
int top = -1;
public void push(int elem) {
if (top < STACK_SIZE - 1) {
arr[++top] = elem;
System.out.println("Element " + elem
+ " is pushed to Stack !");
} else {
System.out.println("Stack Overflow !");
}
}
for(;;){
System.out.println("1: Push 2: Pop 3:Display 4:Exit ");
System.out.println("Enter choice");
publicvoid read()
{
super.read();
Scanner scanner=newScanner(System.in);
System.out.println("Enter the Domain");
domain=scanner.nextLine();
System.out.println("Enter No.of Publications");
publications=scanner.nextInt();
}
}
}
class Technical extends Staff
{
private String skills;
publicvoid read()
{
super.read();
Scanner scanner=newScanner(System.in);
System.out.println("Enter the Skills");
skills=scanner.nextLine();
}
publicvoid display()
{
super.display();
System.out.println("Skills :"+skills);
}
}
class Contract extends Staff
{
private Double period;
publicvoid read()
{
super.read();
Scanner scanner=newScanner(System.in);
System.out.println("Enter the contract period in years");
period=scanner.nextDouble();
}
publicvoid display()
{
super.display();
System.out.println("Contract Period :"+period);
}
classicecream {
publicstaticvoid main(String args[])
{
Staff teaching=new Teaching();
teaching.read();
teaching.display();
}
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 StringTokenizer
class considering the delimiter character as “/”.
)
import java.util.*;
class Customer
{
String name;
String date_of_birth;
String name_date_of_birth;
Scanner key = new Scanner(System.in);
public void read()
{
System.out.println("Enter name");
name=key.next();
System.out.println("Enter date of birth in format dd/mm/yyyy");
date_of_birth=key.next();
name_date_of_birth= "<"+name+","+date_of_birth+">";
System.out.println("The stored data is "+name_date_of_birth);
}
public void display()
{
StringTokenizer ob = new StringTokenizer(name_date_of_birth,"/");
System.out.println("After String Tokenizing using / as
delimiter");
while(ob.hasMoreTokens()){
if(ob.countTokens()>1)
System.out.print(ob.nextToken()+",");
else
System.out.println(ob.nextToken());
}
}
public static void main(String args[])
{
Customer customer = new Customer();
customer.read();
customer.display();
}
}
[CSE Department, CIT-Mandya] Page 6
[Design and Analysis of Algorithms Laboratory-15CSL47 ]
3 (A) Write a Java program to read two integers a and b. Compute a/b and print, when
b is not zero. Raise an exception when b is equal to zero.
import java.util.*;
class exception {
public static void main(String[] args){
float result;
Scanner in = new Scanner(System.in);
System.out.println("Enter numerator : ");
int a = in.nextInt();
System.out.print("Enter denominator : ");
int b = in.nextInt();
try
{
result = a/b;
System.out.println("The result is " +result);
} catch (Exception e) {
System.out.println("Exception Condition,Denominator is zero ");
System.out.println(e);
}
}
}
3(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.
import java.util.*;
}
public class CubeThread extends Thread
{
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println("Cube Thread Printing
Cube("+i+") : "+i*i*i);
Thread.sleep(1000);
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
[CSE Department, CIT-Mandya] Page 8
[Design and Analysis of Algorithms Laboratory-15CSL47 ]
public class Demo {
}
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 divideand- conquer method works along with its time complexity
analysis: worst case, average case and best case.
import java.util.Random;
import java.util.Scanner;
while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
return i;
}
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 divideand- conquer method works along with its time
complexity analysis: worst case, average case and best case.
import java.util.Random;
import java.util.Scanner;
public static void merge(int a[], int low, int mid, int high)
{
int i, j, k;
i=low; j=mid+1; k=low;
while ( i<=mid && j<=high )
{
if( a[i] <= a[j] )
b[k++] = a[i++] ;
else
b[k++] = a[j++] ;
}
while (i<=mid) b[k++] = a[i++] ;
while (j<=high) b[k++] = a[j++] ;
}
6 Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming
method (b) Greedy method.
import java.util.Scanner;
public class Dynamic
{
private int val[][],wt[],p[],x[];
private int n,m;
val=new int[n+1][m+1];
wt=new int[n+1];
p=new int[n+1];
x=new int[n+1];
return K[n][W];
}
}
}
import java.util.Scanner;
public class GreedyKnapsack
{
private double[] p;
private double[] wt;
private double[] take;
private int n,m;
wt=new double[n];
p=new double[n];
take=new double[n];
}
}
System.out.println("=======+============+=======+============+==========");
g.print();
}
}
7 From a given vertex in a weighted connected graph, find shortest paths to other
vertices using Dijkstra's algorithm. Write the program in Java.
import java.util.Scanner;
for(i=1;i<=n;i++)
{
s[i] =0;
d[i] = cost[v][i];
}
s[v] =1;
d[v] = 0;
i = 2;
while (i<=n)
{
u = choose();
s[u] = 1;
i++;
for (w=1;w<=n;w++)
{
if ((d[u]+cost[u][w] < d[w] ) && s[w]==0)
d[w] = d[u] + cost[u][w];
}
}
}
import java.util.Scanner;
c=new int[n][n];
k.cost_adjacency_matrix();
k.minimum_spanning_tree();
}
}
//add u to s
s[u]=1;
c = new int[n][n];
d = new int[n][n];
System.out.println("Enter the adjacency matrix (Enter 999
if there is No edge)");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
c[i][j] = sc.nextInt();
}
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public TSPNearestNeighbour()
{
stack = new Stack<Integer>();
}
while (!stack.isEmpty())
{
element = stack.peek();
i = 1;
min = Integer.MAX_VALUE;
while (i <= numberOfNodes)
{
if (adjacencyMatrix[element][i] > 1 && visited[i] == 0)
{
if (min > adjacencyMatrix[element][i])
{
min = adjacencyMatrix[element][i];
dst = i;
minFlag = true;
}
}
}
(b) Hamiltonian Cycle
import java.util.Scanner;
import java.util.Arrays;
Arrays.fill(path, -1);
graph = g;
try
{
path[0] = 0;
pathCount = 1;
solve(0);
System.out.println("No solution");
}
catch (Exception e)
{
System.out.println(e.getMessage());
display();
}
}
public void solve(int vertex) throws Exception
{
if (graph[vertex][0] == 1 && pathCount == V)
throw new Exception("Solution found");
if (pathCount == V)
return;
if (graph[vertex][v] == 1 )
{
path[pathCount++] = v;
graph[vertex][v] = 0;
graph[v][vertex] = 0;
if (!isPresent(v))
solve(v);
graph[vertex][v] = 1;
graph[v][vertex] = 1;
path[--pathCount] = -1;
}
}
}
public boolean isPresent(int v)
{
for (int i = 0; i < pathCount - 1; i++)
if (path[i] == v)
return true;
return false;
}
public void display()
{
[CSE Department, CIT-Mandya] Page 29
[Design and Analysis of Algorithms Laboratory-15CSL47 ]
System.out.print("\nPath : ");
for (int i = 0; i <= V; i++)
System.out.print(path[i % V] +" ");
System.out.println();
}
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("HamiltonianCycle Algorithm Test\n");
System.out.println("\nEnter matrix\n");
int[][] graph = new int[V][V];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph[i][j] = scan.nextInt();
hc.findHamiltonianCycle(graph);
}
}