Sei sulla pagina 1di 53

||Jai Sri Gurudev||

Sri Adichunchanagiri Shikshana Trust (R)


SJB INSTITUTE OF TECHNOLOGY
BGS HEALTH AND EDUCATION CITY
KENGERI, BANGALORE-560060
(Affiliated to Visvesvaraya Technological University, Belagavi&
Approved by AICTE, New Delhi)

Lab Manual
On

“Design and Analysis of Algorithms Laboratory”


(Sub. Code: 15CSL47)

F or
IV Semester

Prepared By

Mr. Ajay Prakash B.V Mrs. Sunitha K Mrs. Vinutha A. Patil


Assistant Professor, Associate Professor, Assistant Professor,
Dept. of CSE, SJBIT Dept. of CSE, SJBIT Dept. of CSE, SJBIT

Mrs. Kala Chandrashekar.L Mrs. Pavitha G.S Mrs. Chaitra M


Assistant Professor, Assistant Professor, Assistant Professor,
Dept. of CSE, SJBIT Dept. of CSE, SJBIT Dept. of CSE, SJBIT

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

Academic Year: 2016-17


DAA Lab 10CSL47

DESIGN AND ANALYSIS OF ALGORITHM LABORATORY


[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2016 -2017)
SEMESTER – IV

Subject Code: 15CSL47 Exam Marks: 80


IA Marks: 20 Total Number of Lecture Hours: 40
Number of Lecture Hours/Week: 01 I + 02 P Exam Hours: 03

CREDITS – 02

Course objectives: This course will enable students to


x Design and implement various algorithms in JAVA
x Employ various design strategies for problem solving.
x Measure and compare the performance of different algorithms.

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

Course Outcomes: The students should be able to:


x Design algorithms using appropriate design techniques (brute-force, greedy, dynamic
programming, etc.)
x Implement a variety of algorithms such assorting, graph related, combinatorial, etc., in a
high level language.
x Analyze and compare the performance of algorithms using language features.
x Apply and implement learned algorithm design techniques and data structures to solve
real-world problems.
Graduate Attributes
x Engineering Knowledge
x Problem Analysis
x Modern Tool Usage
x Conduct Investigations of Complex Problems
x Design/Development of Solutions
Conduction of Practical Examination:
All laboratory experiments (Twelve problems) are to be included for practical examination.
Students are allowed to pick one experiment from the lot. To generate the data set use random
number generator function. Strictly follow the instructions as printed on the cover page of answer
script for breakup of marks.

Marks distribution: Procedure + Conduction + Viva: 20 + 50 + 10 (80). Change of


experiment is allowed only once and marks allotted to the procedure

Dept. of CSE, SJBIT Page 1


DAA Lab 10CSL47

An algorithm is a description of a procedure which terminates with a result. It is a step by


step procedure designed to perform an operation, and which will lead to the sought result if
followed correctly. Algorithms have a definite beginning and a definite end, and a finite number
of steps. An algorithm produces the same output information given the same input information,
and several short algorithms can be combined to perform complex tasks.

PROPERTIES OF ALGORITHMS

1. Finiteness – an algorithm must terminate after a finite number of steps.

2. Definiteness – each step must be precisely defined.

3. Effective – all operations can be carried out exactly in finite time.

4. Input – an algorithm has one or more outputs.


MODELS OF COMPUTATION

There are many ways to compute the algorithm’s complexity; they are all equivalent in some
sense.

1. Turing machines.

2. Random access machines (RAM).

3. λ Calculus.
4. Recursive functions.

5. Parallel RAM (PRAM).

For the analysis of algorithms, the RAM model is most often employed. Note time does not
appear to be reusable, but space often is.

MEASURING AN ALGORITHM’S COMLEXITY


General consideration of time and space is:

 One time unit per operation.

One space unit per value (all values fit in fixed size register).

There are other considerations:

Dept. of CSE, SJBIT Page 2


DAA Lab 10CSL47

x On real machines, different operations typically take different times to execute. This will
generally be ignored, but sometimes we may wish to count different types of operations,
e.g., Swaps and compares, or additions and multiplications.
x Some operations may be “noise” not truly affecting the running time; we typically only
count “major” operations example, for loop index arithmetic and boundary checking is
 “noise.” operations inside�for�+ loops1 are usually “major.”

x Logarithmic cost model: it takesbits to represent natural number n inbinary notation. Thus
the uniform model of time and space may not bias results for large integers (data).

An algorithm solves an instance of a problem. There is, in general, one parameter, the
input size, denoted by n, which is used to characterize the problem instance. The input size n is
the number of registers needed to hold input (data segment size).

Given n, we’d like to find:

1. The time complexity, denoted by T(n), which is the count of operations the algorithm
performs on the given input.

2. The space complexity, denoted by S(n), which is the number of memory registers used by
the algorithm (stack/heap size, registers).

Note that T(n) and S(n) are relations rather than functions. That is, for different input of the same
size n, T(n) and S(n) may provide different answers.

WORST, AVERAGE, BEST, AND MORTIZED COMPLEXITY


Complexities usually not measured exactly: big- O, Ω, and Θ notation is used.
WORST CASE:

This is the longest time (or most space) that the algorithm will use over all instances of
2
size n. Often this can be represented by a function f(n) such as f(n)=n or f(n)=n lg n. We write
T(n)= O(f(n)) for the worst case time complexity. Roughly, this means the algorithm will take mo
more than f(n) operations.

BEST CASE:

This is the shortest time that the algorithm will use over all instances of size n. often this
2
can be represented by a function f(n) such as f(n)=n or f(n)=n lg n. We write T(n)= Ω (f(n)) for
the best case. Roughly, this means the algorithm will take no less than f(n) operations. The best
case is seldom interesting.
Dept. of CSE, SJBIT Page 3
DAA Lab 10CSL47

When the worst and best case performance of an algorithm are the same we can write
T(n)= Θ (f(n)). Roughly, this says the algorithm always uses f(n) operations on all instances of
size n.

AVERAGE CASE:

This is the average time that the algorithm will use over all instances if size n. it depends
on the probability distribution of instances of the problem.

AMORTIZED COST:

This is used when a sequence of operations occur, e.g., inserts and deletes in a tress, where
the costs vary depending on the operations and their order. For example, some may take a few
steps, some many.

TYPES OF ALGORITHMS

1. Off-line algorithms: all input in memory before time starts, want final result.

2. On-line: input arrives at discrete time steps, intermediate result furnished before next
i nput .

3. Real-time: elapsed time between two inputs (outputs) is a constant O(1).

COMPLEXITY CLASSES

Collection of problems that required roughly the same amount of resources from complexity
classes. Here is a list of the most important:

1. The class P of problems that can be solved in a polynomial number of operations of the
input size on a deterministic Turing machine.

2. The class NP of problems that can be solved in a polynomial number of operations of the
input size on a non-deterministic Turing machine.

3. The class of problems that can be solved in a constant amount of space.

4. The class L that can be solved in a logarithmic amount of space based on the input size.

5. The class PSPACE of problems that can be solved in a polynomial amount of space based
on the input size.

6. The class NC of problems that can be solved in poly-logarithmic time on a polynomial


number of processors.

Dept. of CSE, SJBIT Page 4


DAA Lab 10CSL47

ALGORITHM PARADIGMS

Often there are large collections of problems that can be solved using the same general
techniques or paradigms. A few of the most common are described below:

Brute Force:

A straightforward approach to solving a problem based on the problem statement and


concepts involved. Brute force algorithms are rarely efficient. Example algorithms include:

 B
 ubble sort.
 C
 omputing the sum of n numbers by direct addition.
 S tandard matrix multiplication.

 Linear search.

Divide and Conquer:

Perhaps the most famous algorithm paradigm, divide and conquer is based on partitioning the
problem into two or more smaller sub- problems, solving them and combining the sub-problem
solutions into a solution for the original problem. Example algorithms include:

 x Merge sort and quick sort.

 x The Fast Fourier Transform (FFT).

x Stassen’s matrix multiplication.

Greedy Algorithms:

Greedy algorithms always make the choice that seems best at the moment. This is locally optimal
choice is made with the hope that it leads to a globally optimal solution. Some greedy algorithms
may not be guaranteed to always produce an optimal solution.

Greedy algorithms are often applied to combinatorial optimization problems.

 x Given an instance 1 of the problem.

x There is a set of candidates or feasible solutions that satisfy the constraints of the problem

 x For each feasible solution there is a value determined by an objective function.

x An optimal solution minimizes (or maximizes) the value of objective function.

Dept. of CSE, SJBIT Page 5


DAA Lab 10CSL47

Example algorithms include:

 x Kruskal’s and Prim’s minimal spanning tree algorithms.

 x Dijkstra’s single source shortest path algorithm.

x Huffman coding.

Dynamic Programming:

A nutshell definition of dynamic programming is difficult, but to summarize, problems which


lend themselves to a dynamic programming attack have the following characteristics:

 x We have to search over a large space for an optimal solution.

 x The optimal solution can be expressed in terms of optimal solution to sub-problem.

x The number of sub-problems that must be solved is small.

Dynamic programming algorithms have the following features:

 x A recurrence that is implemented iteratively.

 x A table, built to support the iteration.

x Tracing through the table to find the optimal solution.

Example algorithms include:

  Efficient Fibonacci number computation.

  The Floyd’s, warshall’s, all pairs shortest path algorithm.

  The minimal edit algorithm.

 Optimal polygon triangulation.

Dept. of CSE, SJBIT Page 6


DAA Lab 10CSL47

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

Aim: To illustrate how instance variables and methods are added to the class and to
understand how to create multiple objects for a class. Program also demonstrates how to
initialize the instance members using constructor and the use of „this‟ keyword.

public class Student {


private String usn; // data members
private String name;
private String branch;
private String phoneNumber;
public Student(String usn, String name, String branch, String phoneNumber)
{
// parameterised constructor
this.usn = usn;
this.name = name;
this.branch = branch;
this.phoneNumber = phoneNumber;
}
public String toString() // represents object as a string
{ //method returns the string representation of the object.

return usn + " \t" + name + "\t " + branch + "\t " + phoneNumber;
}

import java.util.Scanner;

// A simple text scanner which can parse primitive types and strings using regular expressions

public classStudentDemo {

public static void main(String[] args) {


// TODO Auto-generated method stub
int i;
String usn;
String name;
String branch;
String phoneNumber;
Scanner scanner = newScanner(System.in);

System.out.println("Enter Number of Students:");

Dept. of CSE, SJBIT Page 7


DAA Lab 10CSL47

int n = scanner.nextInt();
Student[] students=new Student[n];
System.out.println("Enter student details");
for(i=0;i<n;i++)
{
System.out.println("Enter Student "+(i+1)+" Details\n");
System.out.println("Enter Student USN");
usn = scanner.next();
System.out.println("Enter Student NAME");
name = scanner.next();
System.out.println("Enter Student BRANCH");
branch = scanner.next();
System.out.println("Enter Student PHONE NUMBER");
phoneNumber =scanner.next();
students[i]=new Student(usn,name,branch,phoneNumber);
}

System.out.println("USN"+"\t"+"NAME"+"\t"+"BRANCH"+"\t"+"PHONENUMBER");
for(i=0;i<n;i++)
{
System.out.println(students[i]);
}
}
}

Output:

Enter Number of Students


3
Enter student details
Enter Student 1 Details

Enter Student USN


1JB10CS001
Enter Student NAME
Ajay
Enter Student BRANCH
CSE
Enter Student PHONE NUMBER
9886756555

Enter Student 2 Details

Enter Student USN


1JB10CS002
Enter Student NAME

Dept. of CSE, SJBIT Page 8


DAA Lab 10CSL47

Lochan
Enter Student BRANCH
CSE
Enter Student PHONE NUMBER
9845342422

Enter Student 3 Details

Enter Student USN


1JB10CS003
Enter Student NAME
Madhu
Enter Student BRANCH
CSE
Enter Student PHONE NUMBER
8434226573

USN NAME BRANCH PHONENUMBER

1JB10CS001 Ajay CSE 9886756555


1JB10CS002 Lochan CSE 9845342422
1JB10CS003 Madhu CSE 8434226573

Dept. of CSE, SJBIT Page 9


DAA Lab 10CSL47

Program 1b

Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.

Aim: To demonstrate the stack implementation using array. To create exception using
„throw‟ keyword.

public class Stack {


int a[ ];
int top;
public Stack(int n)
{
a=new int[n];
top=-1;
}
void push(int n)
{
if(top==a.length-1)
System.out.println("Stack Overflow");
else
a[++top]=n;
}
int pop()
{
if(top==-1)
{
System.out.println("Stack Underflow");
return 0;
}
else
return(a[top--]);
}
void show()
{
if(top==-1)
System.out.println("Stack Empty");
else
{
System.out.println("Stack elements are");
for(inti=top;i>=0;i--)
System.out.println(a[i]);
}

}
}

Dept. of CSE, SJBIT Page 10


DAA Lab 10CSL47

import java.util.Scanner;
public class StackDemo {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner scanner=new Scanner(System.in);
System.out.println("Enter Size of stack:");
int n = scanner.nextInt();
Stack s = newStack(n);
int item;
while(true)
{
System.out.println("Enter your choice");
System.out.println("1.Push\n2.Pop\n3.Display");
intch=scanner.nextInt();
switch(ch)
{
case 1: System.out.println("Enter the element to be inserted");
item=scanner.nextInt();
s.push(item);
break;
case 2: item=s.pop();
if(item!=0)
System.out.println("Popped element is "+item);
break;
case 3: s.show();
break;
default: System.exit(0);
}
}

Output

Enter Size of stack


5
Enter your choice
1.Push
2.Pop
3.Display
1

Dept. of CSE, SJBIT Page 11


DAA Lab 10CSL47

Enter the element to be inserted


10
Enter your choice
1.Push
2.Pop
3.Display
1
Enter the element to be inserted
20
Enter your choice
1.Push
2.Pop
3.Display
1
Enter the element to be inserted
30
Enter your choice
1.Push
2.Pop
3.Display
1
Enter the element to be inserted
40
Enter your choice
1.Push
2.Pop
3.Display
1
Enter the element to be inserted
50
Enter your choice
1.Push
2.Pop
3.Display
1
Enter the element to be inserted
60
Stack Overflow
Enter your choice
1.Push
2.Pop
3.Display
3
Stack elements are
50
40
30

Dept. of CSE, SJBIT Page 12


DAA Lab 10CSL47

20
10
Enter your choice
1.Push
2.Pop
3.Display
2
Popped element is 50
Enter your choice
1.Push
2.Pop
3.Display
2
Popped element is 40
Enter your choice
1.Push
2.Pop
3.Display
2
Popped element is 30
Enter your choice
1.Push
2.Pop
3.Display
2
Popped element is 20
Enter your choice
1.Push
2.Pop
3.Display
2
Popped element is 10
Enter your choice
1.Push
2.Pop
3.Display
2

Stack Empty

Dept. of CSE, SJBIT Page 13


DAA Lab 10CSL47

PROGRAM 2A

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 atleast 3 staff objects of all
three categories.

package staffdetails;
public class Staff {
protected String staffId;
protected String name;
protected float salary;
protected String phoneNumber;
public Staff(String staffId, String staffName, float staffSalary, String staffPhoneNumber)
{
this.staffId = staffId;
this.name = staffName;
this.salary = staffSalary;
this.phoneNumber = staffPhoneNumber;
}
public String toString() {

return "STAFF ID: " + staffId + "\t" + "NAME: " + name + "\t"
+ "SALARY: " + salary + "\t" + "PHONENUMBER: " +
phoneNumber;
}}
package staffdetails;
public class Teaching extends Staff {
private String domain;
private String publication;

public Teaching(String staffId, String name, float salary,


String phoneNumber, String domain, String publication) {
super(staffId, name, salary, phoneNumber);
this.domain = domain;
this.publication = publication;
}

public String toString() {


return super.toString() + "\t" + "DOMAIN: " + domain + "\t" + "Publications:" +
publication;
}}
package staffdetails;
public class Technical extends Staff {
private String skills;

public Technical(String staffId, String name, float salary,

Dept. of CSE, SJBIT Page 14


DAA Lab 10CSL47

String phoneNumber, String skills) {


super(staffId, name, salary, phoneNumber);
this.skills = skills;
}

public String toString() {


return super.toString() + "\t" + "SKILLS: " + skills;
}}
package staffdetails;
public class Contract extends Staff {
private String period;
public Contract(String staffId, String staffName, float staffSalary,
String staffPhoneNumber, String period) {
super(staffId, staffName, staffSalary, staffPhoneNumber);
this.period = period;
}
public String toString() {
return super.toString() + "\t" + "Period: " + period;
}}

package staffdetails;
import java.util.Scanner;
public class StaffDemo {
public static void main(String[] args) {
int i;
String staffId,name;
float salary;
String phoneNumber, domain, publication, skills, period;
System.out.println("Enter no. of staff to be created for each category(n>=3)");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Teaching[] teachingStaff = new Teaching[n];
Technical[] technicalStaff = new Technical[n];
Contract[] contractStaff = new Contract[n];

System.out.println("Enter Teaching staff details");


for (i = 0; i < n; i++) {
System.out.println("Enter Teaching staff" + (i + 1) + "Details");
System.out.println("Enter Teaching
Details(StaffId,Name,Salary,PhoneNumber,Domain,Publication)");
staffId = in.next();
name = in.next();
salary = in.nextFloat();
phoneNumber = in.next();
domain = in.next();
publication = in.next();
teachingStaff[i] = new Teaching(staffId, name, salary, phoneNumber,domain, publication);

Dept. of CSE, SJBIT Page 15


DAA Lab 10CSL47

}
System.out.println("Enter Technical staff details");
for (i = 0; i < n; i++) {
System.out.println("Enter Technical staff" + (i + 1) + "Details");
System.out.println("Enter Technical staffDetails(StaffId,Name,Salary,PhoneNumber,Skills)");
staffId = in.next();
name = in.next();
salary = in.nextFloat();
phoneNumber = in.next();
skills = in.next();
technicalStaff[i] = new Technical(staffId, name, salary,phoneNumber, skills);
}
System.out.println("Enter Contract staff details");
for (i = 0; i < n; i++) {
System.out.println("Enter Contract staff" + (i + 1) + "Details");
System.out.println("Enter Contract staff details StaffId,Name,Salary,PhoneNumber,Period");
staffId = in.next();
name = in.next();
salary = in.nextFloat();
phoneNumber = in.next();
period = in.next();
contractStaff[i] = new Contract(staffId, name, salary, phoneNumber,period);
}
System.out.println("Teaching Staff Details are as follows");
for (i = 0; i < n; i++) {
System.out.println(teachingStaff[i]);
}
System.out.println("Technical Staff Details are as follows");
for (i = 0; i < n; i++) {
System.out.println(technicalStaff[i]);
}
System.out.println("Contract Staff Details are as follows");
for (i = 0; i < n; i++) {
System.out.println(contractStaff[i]);
}}}

Output

Enter no. of staff to be created for each category(n>=3)

Enter Teaching staff details

Enter Teaching staff 1 Details

Enter Teaching Details(StaffId,Name,Salary,PhoneNumber,Domain,Publication)


Dept. of CSE, SJBIT Page 16
DAA Lab 10CSL47

EMP01
Ajay
20000
9886756555
Java
23
Enter Teaching staff 2 Details
Enter Teaching Details(StaffId,Name,Salary,PhoneNumber,Domain,Publication)
EMP02
Lochan
20000
9845342422
INS
10
Enter Teaching staff 3 Details
Enter Teaching Details(StaffId,Name,Salary,PhoneNumber,Domain,Publication)
EMP03
Madhu
20000
8434226573
IOT
20

Enter Technical staff details


Enter Technical staff 1 Details
Enter Technical staffDetails(StaffId,Name,Salary,PhoneNumber,Skills)
EMP04
Raghu
3000
7345218978
C
Enter Technical staff 2 Details
Enter Technical staffDetails(StaffId,Name,Salary,PhoneNumber,Skills)
EMP05
Swamy
3000
8899242145
Java
Enter Technical staff 3 Details
Enter Technical staffDetails(StaffId,Name,Salary,PhoneNumber,Skills)
EMP06
Karthik
3500
9886721345
CCNA

Dept. of CSE, SJBIT Page 17


DAA Lab 10CSL47

Enter Contract staff details


Enter Contract staff 1 Details
Enter Contract staff details StaffId,Name,Salary,PhoneNumber,Period
EMP07
Girish
5000
7345679021
2
Enter Contract staff 2 Details
Enter Contract staff details StaffId,Name,Salary,PhoneNumber,Period
EMP08
Sathish
6000
9442456783
1
Enter Contract staff 3 Details
Enter Contract staff details StaffId,Name,Salary,PhoneNumber,Period
EMP09
Ravi
5000
9886459023
2
Teaching Staff Details are as follows

STAFF ID: EMP01 NAME: Ajay SALARY: 20000 PHONENUMBER: 9886756555 DOMAIN
Java Publications23
STAFF ID: EMP02 NAME: Lochan SALARY: 20000 PHONENUMBER: 9845342422
DOMAIN INS Publications10
STAFF ID: EMP03 NAME: Madhu SALARY: 20000 PHONENUMBER: 8434226573
DOMAIN IOT Publications20

Technical Staff Details are as follows

STAFF ID: EMP04 NAME: Raghu SALARY: 3000 PHONENUMBER: 7345218978 SKILLS: C
STAFF ID: EMP05 NAME: Swamy SALARY: 3000 PHONENUMBER: 8899242145 SKILLS:
Java
STAFF ID: EMP06 NAME: Karthik SALARY: 3500 PHONENUMBER: 9886721345 SKILLS:
CCNA
Contract Staff Details are as follows

STAFF ID: EMP07 NAME: Girish SALARY: 5000 PHONENUMBER: 7345679021 Period: 2

STAFF ID: EMP08 NAME: Sathish SALARY: 6000 PHONENUMBER: 9442456783Period: 1

STAFF ID: EMP09 NAME: Ravi SALARY: 5000 PHONENUMBER: 9886459023 Period: 2

Dept. of CSE, SJBIT Page 18


DAA Lab 10CSL47

Program 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 “/”.
package customerdemo;
import java.util.StringTokenizer;
public class Customer {
private String customerName;
private String date;
public Customer(String customerName, String date)
{
this.customerName = customerName;
this.date = date;
}
public String toString()
{
String returnValue=customerName;
StringTokenizer tokenizer= new StringTokenizer(date,"/");
System.out.println("The Customer details are ");
while(tokenizer.hasMoreTokens())
{
returnValue=returnValue+","+tokenizer.nextToken();
}
return returnValue;
}}

package customerdemo;

import java.util.Scanner;

public class CustomerDemo {

public static void main(String[] args) {


String customerName;
String date;
Scanner scanner= new Scanner(System.in);
System.out.println("Ënter customer name");
customerName=scanner.next();
System.out.println("Ënter Date (dd/mm/yyyy)");
date=scanner.next();
Customer customer = new Customer(customerName,date);
System.out.println(customer.toString());

}
}

Dept. of CSE, SJBIT Page 19


DAA Lab 10CSL47

Output:

Ënter customer name

Vinay

Enter Date (dd/mm/yyyy)


12/05/1990

The Customer details are

Vinay, 12,05,1990

Dept. of CSE, SJBIT Page 20


DAA Lab 10CSL47

Program 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.
Program:

package daalab;
import java.util.Scanner;
public class Division
{
public static void main(String args[])
{
int a,b;
int quotient;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first number (numerator) : ");
a = scanner.nextInt();
System.out.println("Please enter second number (denominator) : ");
b = scanner.nextInt();
try
{
quotient = a / b;
System.out.println ("Quotient = " + quotient);
}
catch(ArithmeticException ae)
{
System.out.println (ae);
}
}
}

Output:

Run1:

Please enter first number (numerator):


10
Please enter second number (denominator):
2
Quotient: 5

Run2

Please enter first number (numerator):


10
Please enter second number (denominator):
0
java.lang.arithmeticexception / by zero

Dept. of CSE, SJBIT Page 21


DAA Lab 10CSL47

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

package pgm3;

public class Square implementsRunnable{


public intx;
public Square(int x)
{
this.x = x;
}
publicvoidrun()
{
System.out.println("From Second thread - Square of " + x + " is: " + x * x);
}
}

package pgm3;

public class Cube implements Runnable{


public intx;
public Cube(int x)
{
this.x = x;
}
public void run()
{
System.out.println("From Third thread - Cube of " + x + " is: " + x * x * x);
}

package pgm3;
import java.util.*;

public class RandomThread implements Runnable{

public void run()


{
int num ;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)
{

Dept. of CSE, SJBIT Page 22


DAA Lab 10CSL47

num = r.nextInt(100);
System.out.println("First Thread Started and Generated Number is " + num);
Thread.sleep(1000);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}}

package pgm3;

public class MultiThreaded {

public static void main(String[] args) {


try
{
Thread t1=new Thread(new RandomThread());
t1.start();
int num=10;
Thread t2 = new Thread(new Square(num));
t2.start();
Thread t3 = new Thread(new Cube(num));
t3.start();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

Output:

First Thread Started and Generated Number is 23


From Second thread - Square of 10 is 100
From Third thread - Cube of 10 is 1000
First Thread Started and Generated Number is 84
First Thread Started and Generated Number is 15
First Thread Started and Generated Number is 63
First Thread Started and Generated Number is 58

Dept. of CSE, SJBIT Page 23


DAA Lab 10CSL47

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

import java.util.Random;
import java.util.Scanner;
public class Quicksort
{
public static void main(String[] args)
{
System.out.println("Enter the array size");
Scanner in =new Scanner(System.in);
int n=in.nextInt();
int[] a= new int[n];
Random r=new Random();
for(int i=0;i<n;i++)
{
a[i]=r.nextInt(500000);
}
long t1=System.nanoTime();
qsort(a,0,n-1);
long t2=System.nanoTime();
long timetaken = t2 – t1;
System.out.println("Sorted array is");
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
System.out.println("Time taken to sort array is:"+timetaken);

static void qsort(int[] a,int low,int high)


{
if(low<high)
{
int p=partition(a,low,high);
qsort(a,low,p-1);
qsort(a,p+1,high);
}
}

Dept. of CSE, SJBIT Page 24


DAA Lab 10CSL47

static 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;
}
}
return j;
}
}

Output:

Enter the array size


5000
Sorted array is
Time taken to sort array is:
2150757
Enter the array size
10000
Sorted array is
Time taken to sort array is:
3584460

Enter the array size


20000
Dept. of CSE, SJBIT Page 25
DAA Lab 10CSL47

Sorted array is
Time taken to sort array is:
7423970

Enter the array size


30000
Sorted array is
Time taken to sort array is:
10493882

Enter the array size


40000
Sorted array is
Time taken to sort array is:
11522171

Note: Sorted Array elements are not shown in the output because of long list. Tabulate the
time taken for different values of array size and plot the graph.

Dept. of CSE, SJBIT Page 26


DAA Lab 10CSL47

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

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

public class mergesort {

static void merge( int[] array,int low, int mid,int high)


{
int i=low;
int j=mid+1;
int k=low;
int[]resarray;
resarray=new int[high+1];
while(i<=mid&&j<=high)
{
if(array[i]<array[j])
{
resarray[k]=array[i];
i++;
k++;
}
else
{
resarray[k]=array[j];
j++;
k++;
}
}
while(i<=mid)
resarray[k++]=array[i++];
while(j<=high)
resarray[k++]=array[j++];

for(int m=low;m<=high;m++)
array[m]=resarray[m];
}

static void msort( int[] array,int low,int high)


{
if(low<high)
Dept. of CSE, SJBIT Page 27
DAA Lab 10CSL47

{
int mid=(low+high)/2;
msort(array,low,mid);
msort(array,mid+1,high);
merge(array,low,mid,high);
}
}

public static void main(String[] args) {

int[] array;
int i;
System.out.println("Enter the array size");
Scanner in =new Scanner(System.in);
int n=in.nextInt();
array= new int[n];

Random r=new Random();


for( i=0;i<n;i++)
array[i]=r.nextInt(500000);

long startTime=System.nanoTime();
msort(array,0,n-1);
long stopTime=System.nanoTime();

long timetaken =(stopTime-startTime);


System.out.println("Sorted array is");
for(i=0;i<n;i++)
{
System.out.println(array [i]);
}
System.out.println("Time taken to sort array is:"+timetaken);
}
}

Output:

Enter the array size


5000

Sorted array is
Time taken to sort array is 36194636

Dept. of CSE, SJBIT Page 28


DAA Lab 10CSL47

Enter the array size


10000

Sorted array is
Time taken to sort array is 107186583

Enter the array size


20000

Sorted array is
Time taken to sort array is 210228483

Enter the array size


30000

Sorted array is
Time taken to sort array is 728898756

Enter the array size


40000

Sorted array is
Time taken to sort array is 1286540935

Note: Sorted Array elements are not shown in the output because of long list. Tabulate the
time taken for different values of array size and plot the graph.

Dept. of CSE, SJBIT Page 29


DAA Lab 10CSL47

Program 6: Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming
method (b) Greedy method.

(a) Dynamic Programming method

import java.util.Scanner;

public class knapsackDP {


public void solve(int[] wt, int[] val, int W, int N)
{
int i,j;
int[][] sol = new int[N + 1][W + 1];
for ( i = 0; i <= N; i++)
{
for ( j = 0; j <= W; j++)
{
if(i==0||j==0)
sol[i][j]=0;
else if(wt[i]>j)
sol[i][j]=sol[i-1][j];
else
sol[i][j]=Math.max((sol[i-1][j]), (sol[i - 1][j - wt[i]] + val[i]));
}
}
System.out.println("The optimal solution is"+sol[N][W]);
int[] selected = new int[N1];
for(i=0;i<N+1;i++) selected[i]=0;
i=N;
j=W;
while (i>0&&j>0)
{
if (sol[i][j] !=sol[i-1][j])
{
selected[i] = 1;
j = j - wt[i];
}
i--;
}
System.out.println("\nItems selected :");
for ( i = 1; i < N + 1; i++)
if (selected[i] == 1)
System.out.print(i +" ");
System.out.println();
}
public static void main(String[] args) {

Dept. of CSE, SJBIT Page 30


DAA Lab 10CSL47

Scanner scan = new Scanner(System.in);


knapsackDP ks = new knapsackDP();
System.out.println("Enter number of elements ");
int n = scan.nextInt();
int[] wt = new int[n + 1];
int[] val = new int[n + 1];
System.out.println("\nEnter weight for "+ n +"elements");
for (int i = 1; i <= n; i++)
wt[i] = scan.nextInt();
System.out.println("\nEnter value for "+ n +"elements");
for (int i = 1; i <= n; i++)
val[i] = scan.nextInt();

System.out.println("\nEnter knapsack weight ");


int W = scan.nextInt();
ks.solve(wt, val, W, n);
}
}

Output:

Enter number of
elements 4
Enter weight for 4
elements 2 1 3 2

Enter value for 4


elements 12 10 20 15

Enter knapsack
weight 5
The optimal solutionis37
Items selected :
124

Dept. of CSE, SJBIT Page 31


DAA Lab 10CSL47

(b)Greedy method.

import java.util.Scanner;
public class knapsacgreedy {
public static void main(String[] args) {
int i,j=0,max_qty,m,n;
float sum=0,max;
Scanner sc = new Scanner(System.in);
int array[][]=new int[2][20];
System.out.println("Enter no of items");
n=sc.nextInt();
System.out.println("Enter the weights of each items");
for(i=0;i<n;i++)
array[0][i]=sc.nextInt();
System.out.println("Enter the values of each items");

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

System.out.println("Enter maximum volume of knapsack :");


max_qty=sc.nextInt();
m=max_qty;
while(m>=0)
{
max=0;
for(i=0;i<n;i++)
{
if(((float)array[1][i])/((float)array[0][i])>max)
{
max=((float)array[1][i])/((float)array[0][i]);
j=i; }
}
if(array[0][j]>m)
{
System.out.println("Quantity of item number: "+ (j+1) + " added is " +m);
sum+=m*max;
m=-1;
}
else
{
System.out.println("Quantity of item number: " + (j+1) + " added is " + array[0][j]); m-
=array[0][j];
sum+=(float)array[1][j];

array[1][j]=0;
}

Dept. of CSE, SJBIT Page 32


DAA Lab 10CSL47

System.out.println("The total profit is " + sum); sc.close();

Output:

Enter no of items 4

Enter the weights of each items


2132

Enter the values of each items 12 10 20 15

Enter maximum volume of knapsack : 5

Quantity of item number: 2 added is 1

Quantity of item number: 4 added is 2

Quantity of item number: 3 added is 2

The total profit is 38.333332

Dept. of CSE, SJBIT Page 33


DAA Lab 10CSL47

PROGRAM 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;

public class Dijkstra {

int d[]=new int[10];


int p[]=new int[10];
int visited[]=new int[10];
public void dijk(int[][]a, int s, int n)
{
int u=-1,v,i,j,min;
for(v=0;v<n;v++)
{
d[v]=99;
p[v]=-1;
}
d[s]=0;
for(i=0;i<n;i++){
min=99;
for(j=0;j<n;j++){
if(d[j]<min&& visited[j]==0)
{
min= d[j];
u=j;
}
}
visited[u]=1;
for(v=0;v<n;v++){
if((d[u]+a[u][v]<d[v])&&(u!=v)&&visited[v]==0)
{
d[v]=d[u]+a[u][v];
p[v]=u;
}
}

void path(int v,int s)


{
if(p[v]!=-1)
path(p[v],s);
if(v!=s)

Dept. of CSE, SJBIT Page 34


DAA Lab 10CSL47

System.out.print("->"+v+" ");
}
void display(int s,int n)
{
int i;
for(i=0;i<n;i++)
{
if(i!=s){
System.out.print(s+" ");
path(i,s);

if(i!=s)

System.out.print("="+d[i]+"");

System.out.println();

public static void main(String[] args) {

int a[][]=new

int[10][10]; int i,j,n,s;

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


Scanner sc = new Scanner(System.in);
n=sc.nextInt();
System.out.println("enter the weighted matrix");

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

for(j=0;j<n;j++)

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

System.out.println("enter the source vertex");


s=sc.nextInt();
Dijkstra tr=new Dijkstra();

tr.dijk(a,s,n);

System.out.println("the shortest path between source"+s+"to remaining vertices are");

Dept. of CSE, SJBIT Page 35


DAA Lab 10CSL47

tr.display(s,n);
sc.close();

Output:

Enter the number of vertices 5

Enter the weighted matrix

0 3 99 7 99

3 0 4 2 99

99 4 0 5 6

5 2 5 0 4

99 99 6 4 0

Enter the source vertex 0

The shortest path between source 0 to remaining vertices are

0 ->1 =3

0 ->1 ->2 =7
0 ->1 ->3 =5
0 ->1 ->3 ->4 =9

Dept. of CSE, SJBIT Page 36


DAA Lab 10CSL47

Program 8: Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's
algorithm

import java.util.Scanner;

public class kruskal


{
int parent[ ]=new int[10];

int find(int m)
{
int p=m; while(parent[p]!=0)
p=parent[p];
return p;
}

void union(int i,int j)


{
if(i<j) parent[i]=j;
else
parent[j]=i;
}

void krkl(int[][]a, int n)


{
int u=0,v=0,min,k=0,i,j,sum=0;
while(k<n-1)
{
min=99;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(a[i][j]<min&&i!=j)
{
min=a[i][j];
u=i;
v=j;
}
i=find(u);
j=find(v);
if(i!=j)
{
union(i,j);
System.out.println("("+u+","+v+")"+"="+a[u][v]); sum=sum+a[u][v];
k++;
}
a[u][v]=a[v][u]=99;
}

Dept. of CSE, SJBIT Page 37


DAA Lab 10CSL47

System.out.println("The cost of minimum spanning tree = "+sum);


}

public static void main(String[] args)


{
int a[ ][ ]=new int[10][10];
int i,j;
System.out.println("Enter the number of vertices of the graph");

Scanner in=new Scanner(System.in);

int n;
n=in.nextInt();
System.out.println("Enter the wieghted matrix"); for(i=1;i<=n;i++)
for(j=1;j<=n;j++) {
a[i][j]=in.nextInt(); }

kruskal k=new kruskal();


k.krkl(a,n);
in.close();
}
}

Output:
Enter the number of vertices of the graph
6
Enter the weighted matrix
0 3 99 99 6 5
3 0 1 99 99 4
99 1 0 6 99 4
99 99 6 0 8 5
6 99 99 8 0 2
5 4 4 5 2 0

(2,3)=1 (5,6)=2 (1,2)=3 (2,6)=4 (4,6)=5

The cost of minimum spanning tree = 15

Dept. of CSE, SJBIT Page 38


DAA Lab 10CSL47

Program 9. Find Minimum Cost Spanning Tree of a given undirected graph using Prim's
algorithm. Implement the program in Java language.
import java.util.Scanner;
public class prims
{
public static void main(String[] args)
{
int w[ ][ ]=new int[10][10];
int n,i,j,s,k=0;
int min;
int sum=0;
int u=0,v=0;
int flag=0;
int sol[ ]=new int[10];
System.out.println("Enter the number of vertices");
Scanner in=new Scanner(System.in);
n=in.nextInt();
for(i=1;i<=n;i++){
sol[i]=0;
}
System.out.println("Enter the weighted graph");
for(i=1;i<=n;i++) {
for(j=1;j<=n;j++){
w[i][j]=in.nextInt();
}
}
System.out.println("Enter the source vertex");
s=in.nextInt();
sol[s]=1;
k=1;
while (k<=n-1)
{
min=99;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(sol[i]==1&&sol[j]==0) if(i!=j&&min>w[i][j])
{
min=w[i][j];
u=i;
v=j;
}
sol[v]=1;
sum=sum+min;
k++; System.out.println(u+"->"+v+"="+min);
}
for(i=1;i<=n;i++)

Dept. of CSE, SJBIT Page 39


DAA Lab 10CSL47

if(sol[i]==0) flag=1;
if(flag==1)
System.out.println("No spanning tree");
else
System.out.println("The cost of minimum spanning tree is"+sum);
in.close(); } }
Output:

Enter the number of vertices

Enter the weighted graph

0 3 99 99 6 5

3 0 1 99 99 4

99 1 0 6 99 4

99 99 6 0 8 5

6 99 99 8 0 2

5 4 4 5 2 0

Enter the source vertex

1->2=3

2->3=1

2->6=4

6->5=2

6->4=5

The cost of minimum spanning tree is15

Dept. of CSE, SJBIT Page 40


DAA Lab 10CSL47

Program 10 A:
Write Java programs to (a) Implement All-Pairs Shortest Paths problem using Floyd's
algorithm.
import java.util.Scanner;
public class floyd {
void flyd(int[][] w,int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
w[i][j]=Math.min(w[i][j], w[i][k]+w[k][j]);
}
public static void main(String[]args) {
int a[][]=new int[10][10];
int n,i,j;
System.out.println("enter the number of vertices");
Scanner sc=new Scanner(System.in); n=sc.nextInt();
System.out.println("Enter the weighted matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
a[i][j]=sc.nextInt();
floyd f=new floyd();
f.flyd(a, n);
System.out.println("The shortest path matrix is"); for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
sc.close(); } }
Output:
Enter the number of vertices 4
Enter the weighted matrix
0 99 3 99
2 0 99 99
99 7 0 1
6 99 99 0
The shortest path matrix is
0 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0

Dept. of CSE, SJBIT Page 41


DAA Lab 10CSL47

Program 10B: Write Java programs to Implement All-Pairs Shortest Paths problem using
Travelling Sales Person problem using Dynamic programming.

import java.util.Scanner;

class TSPExp {
int weight [][],n,tour[],finalCost;
final int INF=1000;
TSPExp()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no. of
nodes:=>"); n=s.nextInt();
weight=new int[n][n];
tour=new int[n-1];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
System.out.print("Enter weight of"+(i+1)+" to "+(j+1)+":=>");
weight[i][j]=s.nextInt();
}
}
}
System.out.println();
System.out.println("Starting node assumed to be node 1.");
eval();
}

public int COST(int currentNode,int inputSet[],int setSize)


{
if(setSize==0)
return weight[currentNode][0];

int min=INF;
int setToBePassedOnToNextCallOfCOST[]=new
int[n-1];
for(int i=0;i<setSize;i++)
{
int k=0;//initialise new set
for(int j=0;j<setSize;j++)

Dept. of CSE, SJBIT Page 42


DAA Lab 10CSL47

{
if(inputSet[i]!=inputSet[j])

setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) <min)
{
min=weight[currentNode][inputSet[i]]+temp;
}
}
return min;
public int MIN(int currentNode,int inputSet[],int setSize)
{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
int setToBePassedOnToNextCallOfCOST[]= new int[n-1];
for(int i=0;i<setSize;i++)//considers each node of inputSet
{
int k=0;
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];

}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
minindex=inputSet[i];
}
}
return minindex;

public void eval()


{

int dummySet[]=new int[n-1];


for(int i=1;i<n;i++)
dummySet[i-1]=i;
finalCost=COST(0,dummySet,n-1);
constructTour();
}

Dept. of CSE, SJBIT Page 43


DAA Lab 10CSL47

public void constructTour()


{

int previousSet[]=new int[n-1];


int nextSet[]=new int[n-2];
for(int i=1;i<n;i++) previousSet[i-1]=i;
int setSize=n-1;
tour[0]=MIN(0,previousSet,setSize);

for(int i=1;i<n-1;i++)
{
int k=0;
for(int j=0;j<setSize;j++)
{
if(tour[i-1]!=previousSet[j])
nextSet[k++]=previousSet[j];
}
--setSize; tour[i]=MIN(tour[i-1],nextSet,setSize);
for(int j=0;j<setSize;j++)
previousSet[j]=nextSet[j];
}
display();
}

public void display()


{
System.out.println();
System.out.print("The tour is 1-");
for(int i=0;i<n-1;i++)
System.out.print((tour[i]+1)+"-");
System.out.print("1");
System.out.println();
System.out.println("The final cost is "+finalCost);
}

}
class TSP
{
public static void main(String args[])
{
TSPExp obj=new TSPExp();
}
}

Dept. of CSE, SJBIT Page 44


DAA Lab 10CSL47

Output:

Enter no. Of nodes:=> 4

Enter weight of 1 to 2:=>2

Enter weight of 1 to 3:=>5

Enter weight of 1 to 4:=>7

Enter weight of 2 to 1:=>2

Enter weight of 2 to 3:=>8

Enter weight of 2 to 4:=>3

Enter weight of 3 to 1:=>5

Enter weight of 3 to 2:=>8

Enter weight of 3 to 4:=>1

Enter weight of 4 to 1:=>7

Enter weight of 4 to 2:=> 3

Enter weight of 4 to 3:=>1

Starting node assumed to be node 1.

The tour is 1-2-4-3-1

The final cost is 11

Dept. of CSE, SJBIT Page 45


DAA Lab 10CSL47

Program 11: Design and implement in Java to find a subset of a given set S = {Sl, S2,.....,Sn}
of n positive integers whose SUM is equal to a given positive integer d. For example, if S ={1,
2, 5,6, 8} and d= 9, there are two solutions {1,2,6}and {1,8}. Display a suitable message, if the
given problem instance doesn't have a solution.

import java.util.Scanner;
import java.lang.Math;
public class subSet {
void subset(int num,int n, int x[])
{
i nt i ;

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

x[i]=0;

for(i=n;num!=0;i--)

{
x[i]=num%2;

num=num/2;
}
}

public static void main(String[] args) {

int a[]=new int[10];


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

int j;

System.out.println("enter the number of elements of set");


Scanner sc=new Scanner(System.in);
n=sc.nextInt();

System.out.println("enter the elements of set");


for(int i=1;i<=n;i++)
a[i]=sc.nextInt();

System.out.println("enter the positive integer sum"); d=sc.nextInt();

if(d>0)
{

Dept. of CSE, SJBIT Page 46


DAA Lab 10CSL47

for(int i=1;i<=Math.pow(2,n)-1;i++)
{
subSet s=new subSet();
s.subset(i,n,x);
sum=0;
for(j=1;j<=n;j++)
if(x[j]==1)
sum=sum+a[j];
if(d==sum)
{
System.out.print("Subset={");
present=1;
for(j=1;j<=n;j++)
if(x[j]==1)
System.out.print(a[j]+",");

System.out.print("}="+d);
System.out.println();
}
}
}
if(present==0)
System.out.println("Solution does not exists");

Output:

enter the number of elements of set 5

enter the elements of set 1 2 5 6 8

enter the positive integer sum 9

Subset={1,8,}=9
Subset={1,2,6,}=9

Dept. of CSE, SJBIT Page 47


DAA Lab 10CSL47

Program 12: Design and implement the presence of Hamiltonian Cycle in an


undirected Graph G of n vertices.

import java.util.*;
class Hamiltoniancycle
{
private int adj[][],x[],n;
public Hamiltoniancycle()
{
Scanner src = new Scanner(System.in);
System.out.println("Enter the number of nodes"); n=src.nextInt();
x=new int[n];
x[0]=0;
for (int i=1;i<n;i++)
x[i]=-1;

adj=new int[n][n];
System.out.println("Enter the adjacency matrix");
for (int i=0;i<n; i++)
for (int j=0; j<n; j++)
adj[i][j]=src.nextInt();
}
public void nextValue (int k)
{
int i=0;
while(true)
{
x[k]=x[k]+1;
if (x[k]==n)
x[k]=-1;
if(x[k]==-1)
return;
if (adj[x[k-1]][ x[k]]==1)
for (i=0; i<k; i++)
if (x[i]==x[k])
break;
if (i==k)
if (k<n-1 || k==n-1 &&
adj[x[n-1]][0]==1) return;
}
}
public void getHCycle(int k)
{
while(true)
{

Dept. of CSE, SJBIT Page 48


DAA Lab 10CSL47

nextValue(k);
if (x[k]==-1)
return;
if (k==n-1)
{
System.out.println("\nSolution :");
for (int i=0; i<n; i++)
System.out.print((x[i]+1)+"");
System.out.println(1);
}
else getHCycle(k+1);
}
}
class HamiltoniancycleExp
{
public static void main(String args[])
{
Hamiltoniancycle obj=new Hamiltoniancycle();
obj.getHCycle(1);
}
}

Output:

Enter the number of nodes 6


Enter the adjacency matrix
0 1 1 1 0 0
1 0 1 0 0 1
1 1 0 1 1 0
1 0 1 0 1 0
0 0 1 1 0 1
0 1 0 0 1 0

Solution :
1 265 341
Solution :
1 265 431
Solution :
1 326 541
Solution :
1 345 621
Solution :
1 435 621
Solution :
1 456 231

Dept. of CSE, SJBIT Page 49


DAA Lab 10CSL47

VIVA QUESTIONS

1. What is an algorithm? What is the need to study Algorithms?

2. Explain Euclid’s Algorithm to find GCD of two integers with an e.g.


3. Explain Consecutive Integer Checking algorithm to find GCD of two numbers with an e.g.
4. Middle School Algorithm with an e.g.

5. Explain the Algorithm design and analysis process with a neat diagram.

6. Define: a) Time Efficiency b) Space Efficiency.

7. What are the important types of problems that encounter in the area of computing?

8. What is a data structure? How are data structures classified?

9. Briefly explain linear and non-linear data structures.

10. What is a set? How does it differ from a list?

11. What are the different operations that can be performed on a set?

12. What are the different ways of defining a set?

13. How can sets be implemented in computer application?

14. What are different ways of measuring the running time of an algorithm?

15. What is Order of Growth?

16. Define Worst case, Average case and Best case efficiencies.

17. Explain the Linear Search algorithm.

18. Define O, Ω, Ө notations.

19. Give the general plan for analyzing the efficiency of non-recursive algorithms with an e.g.
20. Give an algorithm to find the smallest element in a list of n numbers and analyze the
efficiency.
21. Give an algorithm to check whether all the elements in a list are unique or not and analyze
the efficiency
22. Give an algorithm to multiply two matrices of order N*N and analyze the efficiency.

23. Give the general plan for analyzing the efficiency of Recursive algorithms with an e.g.

24. Give an algorithm to compute the Factorial of a positive integer n and analyze the
efficiency.
25. Give an algorithm to solve the Tower of Hanoi puzzle and analyze the efficiency.

26. Define an explicit formula for the nth Fibonacci number.

27. Define a recursive algorithm to compute the nth Fibonacci number and analyze its
efficiency.
28. What is Exhaustive Search?

29. What is Traveling Salesmen Problem (TSP)? Explain with e.g.

30. Give a Brute Force solution to the TSP. What is the efficiency of the algorithm?

31. What is an Assignment Problem? Explain with an e.g.

32. Give a Brute Force solution to the Assignment Problem. What is the efficiency of the
Dept. of CSE, SJBIT Page 50
DAA Lab 10CSL47


algorithm?

33. Explain Divide and Conquer technique and give the general divide and conquer
recurrence.
34. Define: a)Eventually non-decreasing function b)Smooth function c)Smoothness rule
d)Masters theorem
35. Explain the Merge Sort algorithm with an e.g. and also draw the tree structure of the
recursive calls made.
36. Analyze the efficiency of Merge sort algorithm.
37. Explain the Quick Sort algorithm with an example and also draw the tree structure of the
recursive calls made.
38. Analyze the efficiency of Quick sort algorithm.
39. Give the Binary Search algorithm and analyze the efficiency.
40. Give an algorithm to find the height of a Binary tree and analyze the efficiency.
41. Give an algorithm each to traverse the Binary tree in Inorder, Preorder and Postorder.
42. Explain how do you multiply two large integers and analyze the efficiency of the
algorithm. Give an e.g.
43. Explain the Stassen’s Matrix multiplication with an e.g. and analyze the efficiency.
44. Explain the concept of Decrease and Conquer technique and explain its three major
variations.
45. Give the Insertion Sort algorithm and analyze the efficiency.
46. Explain DFS and BFS with an e.g. and analyze the efficiency.
47. Give two solutions to sort the vertices of a directed graph topologically.
48. Discuss the different methods of generating Permutations.
49. Discuss the different methods of generating Subsets.
50. What is Heap? What are the different types of heaps?
51. Explain how do you construct heap?
52. Explain the concept of Dynamic programming with an e.g.
53. What is Transitive closure? Explain how do you find out the Transitive closure with an
e.g.
54. Give the Warshall’s algorithm and analyze the efficiency.
55. Explain how do you solve the All-Pairs-Shortest-Paths problem with an e.g.
56. Give the Floyd’s algorithm and analyze the efficiency.
57. What is Knapsack problem? Give the solution to solve it using dynamic programming
technique.
58. What are Memory functions? What are the advantages of using memory functions?
59. Give an algorithm to solve the knapsack problem.
60. Explain the concept of Greedy technique.
61. Explain Prim’s algorithm with e.g.
62. Prove that Prim’s algorithm always yields a minimum spanning tree.
63. Explain Kruskal’s algorithm with an e.g.
Dept. of CSE, SJBIT Page 51
DAA Lab 10CSL47

64. Explain Dijkstra’s algorithm with an e.g.


65. What are Huffman trees? Explain how to construct a Huffman trees with an e.g.
66. Explain the concept of Backtracking with an e.g.
67. What is state space tree? Explain how to construct a state space tree?
68. What is n-Queen’s problem? Generate the state space tree for n=4.
69. Explain the subset sum problem with an e.g.
70. What are Decision Trees? Explain.
71. Define P, NP, and NP-Complete problems.
72. Explain the Branch and Bound technique with an e.g.

Dept. of CSE, SJBIT Page 52

Potrebbero piacerti anche