Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Lab Manual
On
F or
IV Semester
Prepared By
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
PROPERTIES OF ALGORITHMS
There are many ways to compute the algorithm’s complexity; they are all equivalent in some
sense.
1. Turing machines.
3. λ Calculus.
4. Recursive functions.
For the analysis of algorithms, the RAM model is most often employed. Note time does not
appear to be reusable, but space often is.
One space unit per value (all values fit in fixed size register).
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).
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.
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 .
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.
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.
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:
B
ubble sort.
C
omputing the sum of n numbers by direct addition.
S tandard matrix multiplication.
Linear search.
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:
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.
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 Huffman coding.
Dynamic Programming:
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.
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 {
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:
Lochan
Enter Student BRANCH
CSE
Enter Student PHONE NUMBER
9845342422
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.
}
}
import java.util.Scanner;
public class StackDemo {
Output
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
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;
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 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
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
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
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: EMP09 NAME: Ravi SALARY: 5000 PHONENUMBER: 9886459023 Period: 2
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;
}
}
Output:
Vinay
Vinay, 12,05,1990
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:
Run2
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;
package pgm3;
package pgm3;
import java.util.*;
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;
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 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);
Output:
Sorted array is
Time taken to sort array is:
7423970
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.
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;
for(int m=low;m<=high;m++)
array[m]=resarray[m];
}
{
int mid=(low+high)/2;
msort(array,low,mid);
msort(array,mid+1,high);
merge(array,low,mid,high);
}
}
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];
long startTime=System.nanoTime();
msort(array,0,n-1);
long stopTime=System.nanoTime();
Output:
Sorted array is
Time taken to sort array is 36194636
Sorted array is
Time taken to sort array is 107186583
Sorted array is
Time taken to sort array is 210228483
Sorted array is
Time taken to sort array is 728898756
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.
Program 6: Implement in Java, the 0/1 Knapsack problem using (a) Dynamic Programming
method (b) Greedy method.
import java.util.Scanner;
Output:
Enter number of
elements 4
Enter weight for 4
elements 2 1 3 2
Enter knapsack
weight 5
The optimal solutionis37
Items selected :
124
(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();
array[1][j]=0;
}
Output:
Enter no of items 4
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;
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();
int a[][]=new
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j]=sc.nextInt();
tr.dijk(a,s,n);
tr.display(s,n);
sc.close();
Output:
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
0 ->1 =3
0 ->1 ->2 =7
0 ->1 ->3 =5
0 ->1 ->3 ->4 =9
Program 8: Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's
algorithm
import java.util.Scanner;
int find(int m)
{
int p=m; while(parent[p]!=0)
p=parent[p];
return p;
}
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(); }
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
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++)
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:
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
1->2=3
2->3=1
2->6=4
6->5=2
6->4=5
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
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();
}
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++)
{
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;
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();
}
}
class TSP
{
public static void main(String args[])
{
TSPExp obj=new TSPExp();
}
}
Output:
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;
}
}
int j;
if(d>0)
{
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:
Subset={1,8,}=9
Subset={1,2,6,}=9
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)
{
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:
Solution :
1 265 341
Solution :
1 265 431
Solution :
1 326 541
Solution :
1 345 621
Solution :
1 435 621
Solution :
1 456 231
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