Download Design and Analysis of Algorithm Laboratory CANARA

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CANARA ENGINEERING COLLEGE
(Affiliated to VTU, Approved by AICTE)
Benjanpadavu – 574 219, Bantwal Taluk, D.K. Dist. Karnataka
Department of Computer Science & Engineering
B.E 4th semester
DESIGN AND ANALYSIS OF ALGORITHM LABORATORY
(15CSL47)
Lab Manual
Prepared By
Prof. Abhishek S. Rao
&
Prof. Santosh
VISVESVARAYA TECHNOLOGICAL UNIVERSITY
“Jnana Sangama”, BELAGAVI – 590 018
KARNATAKA
Design and Analysis of Algorithm Laboratory
INDEX
SL.
NO
I.
1
2
3
4
CONTENTS
PAGE-NO
COURSE
OBJECTIVE,
COURSE
DESCRIPTION, COURSE
OUTCOMES
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.
B. Write a Java program to implement the Stack using arrays. Write
Push(), Pop(), and Display() methods to demonstrate its working.
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 StringTokenizer class considering the
delimiter character as “/”.
A. Write a Java program to read two integers a and b. Compute a/b and
print, when b is not zero. Raise an exception when b is equal to zero.
B. Write a Java program that implements a multi-thread application that
has three threads. First thread generates a random integer for every 1
second; second thread computes the square of the number and prints;
third thread will print the value of cube of 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
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
5 - 11
12 - 17
18 - 21
22 - 23
Page 2
Design and Analysis of Algorithm Laboratory
along with its time complexity analysis: worst case, average case and best case.
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
5
24 - 25
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.
Implement in Java, the 0/1 Knapsack problem using
6
26 - 30
(a) Dynamic Programming method
(b) Greedy method.
From a given vertex in a weighted connected graph, find shortest paths to other
7
31 - 32
vertices using Dijkstra's algorithm. Write the program in Java.
Find Minimum Cost Spanning Tree of a given undirected graph using
8
33 - 37
(a) Kruskal's algorithm
(b) Prim's algorithm. Implement the program in Java language.
Write Java programs to
9
38 - 43
(a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
(b) Implement Travelling Sales Person problem using Dynamic programming.
(a) 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
10
44 - 49
{1,2,6}and {1,8}. Display a suitable message, if the given problem instance
doesn't have a solution.
(b) Design and implement the presence of Hamiltonian Cycle in an undirected
Graph G of n vertices.
CONDUCTION OF PRACTICAL EXAMINATION:
Instructions:
1. All laboratory experiments (TEN problems) are to be included for practical examination.
Students are allowed to pick one experiment from the lot.
2. To generate the data set use random number generator function.
3. Strictly follow the instructions as printed on the cover page of answer script for breakup
of marks.
4. 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, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 3
Design and Analysis of Algorithm Laboratory
COURSE OBJECTIVE
This course will enable students to:
Design and implement various algorithms in JAVA
Employ various design strategies for problem solving.
Measure and compare the performance of different algorithms.
COURSE 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
After studying this course, students will be able to:
Design algorithms using appropriate design techniques (brute-force, greedy,
dynamic programming, etc.)
Implement a variety of algorithms such assorting, graph related, combinatorial,
etc., in a high level language.
Analyze and compare the performance of algorithms using language features.
Apply and implement learned algorithm design techniques and data structures to
solve real world problems.
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 4
Design and Analysis of Algorithm Laboratory
1.
a. Create a Java class called Student with the following details as variables within it.
(v)
USN
(vi)
Name
(vii) Branch
(viii) 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;
int phone;
Student(String usn,String name,String branch,int phone)
{
this.usn=usn;
this.name=name;
this.branch=branch;
this.phone=phone;
}
public static void main(String a[])
{
Scanner s1=new Scanner(System.in);
Student s[]=new Student[5];
String usn;
String name;
String branch;
int phone;
int n;
System.out.println("Enter the number of Students");
n=s1.nextInt();
System.out.println("Enter Student Details: USN
PHONE_NO");
for(int i=0;i<n;i++)
{
usn=s1.next();
Dept. of CSE, CEC
NAME
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
BRANCH
Page 5
Design and Analysis of Algorithm Laboratory
name=s1.next();
branch=s1.next();
phone=s1.nextInt();
s[i]=new Student(usn,name,branch,phone);
}
System.out.println("Student Details");
System.out.println("USN\tNAME\tBRANCH\tPHONE");
for(int i=0;i<n;i++)
{
System.out.println(s[i].usn+"\t"+s[i].name+"\t"+s[i].branch
+"\t"+s[i].phone);
}
}
}
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 6
Design and Analysis of Algorithm Laboratory
Output:
Enter the number of Students
3
Enter Student Details: USN NAME BRANCH PHONE_NO
100 Abhi CSE 8888
200 Santosh ISE 9999
300 Amar ECE 7777
Student Details
USN
NAME
100
Abhi
200
Santosh
300
Amar
Dept. of CSE, CEC
BRANCH
CSE
ISE
ECE
PHONE
8888
9999
7777
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 7
Design and Analysis of Algorithm Laboratory
b. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and
Display() methods to demonstrate its working.
import java.io.IOException;
import java.util.Scanner;
class Stack
{
private int top;
private int item[];
Stack(int size)
{
top = -1;
item = new int[size];
}
void pushItem(int data)
{
if (top == item.length - 1)
{
System.out.println("Stack is Full");
}
else
{
item[++top] = data;
System.out.println("Pushed Item :" + item[top]);
}
}
int popItem()
{
if (top < 0)
{
System.out.println("Stack Underflow");
return 0;
}
else
{
System.out.println("Pop Item : " + item[top]);
return item[top--];
}
}
public void displayStack()
{
if (top >= 0)
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 8
Design and Analysis of Algorithm Laboratory
{
System.out.println("Elements in stack are:");
for (int i = 0; i <= top; i++)
{
System.out.println(item[i]);
}
}
else
{
System.out.println("Stack is Empty");
}
}
}
class StackExample
{
public static void main(String[] args) throws IOException
{
Stack stk = new Stack(5);
boolean yes=true;
int choice;
Scanner s=new Scanner(System.in);
do
{
System.out.println("\n");
System.out.println("1).Push\n2).Pop\n3).Display\n4).Exit\n\nEnter
Choice");
choice = s.nextInt();
switch(choice)
{
case 1: System.out.println("Enter Push Item: ");
stk.pushItem(s.nextInt());
break;
case 2: stk.popItem();break;
case 3: stk.displayStack();break;
case 4: System.exit(0);break;
default: System.out.println("Invalid Choice");
}
}while(yes==true);
s.close();
}
}
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 9
Design and Analysis of Algorithm Laboratory
Output:
1).Push
2).Pop
3).Display
4).Exit
Enter Choice
1
Enter Push Item:
10
Pushed Item: 10
1).Push
2).Pop
3).Display
4).Exit
Enter Choice
1
Enter Push Item:
20
Pushed Item: 20
1).Push
2).Pop
3).Display
4).Exit
Enter Choice
3
Elements in stack are:
10
20
1).Push
2).Pop
3).Display
4).Exit
Enter Choice
2
Pop Item: 20
1).Push
2).Pop
Dept.
of CSE, CEC
3).Display
4).Exit
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 10
Design and Analysis of Algorithm Laboratory
Enter Choice
3
Elements in stack are:
10
1).Push
2).Pop
3).Display
4).Exit
Enter Choice
2
Pop Item: 10
1).Push
2).Pop
3).Display
4).Exit
Enter Choice
3
Stack is Empty
1).Push
2).Pop
3).Display
4).Exit
Enter Choice
2
Stack Underflow
1).Push
2).Pop
3).Display
4).Exit
Enter Choice
4
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 11
Design and Analysis of Algorithm Laboratory
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.
package adaprograms;
import java.io.IOException;
import java.util.Scanner;
class Staff
{
int staffid;
String name;
long phone;
float salary;
Staff(int staffid, String name, long phone,float salary)
{
this.staffid=staffid;
this.name=name;
this.phone=phone;
this.salary=salary;
}
}
class Teaching extends Staff
{
String domain;
String publication;
Teaching(int staffid, String name, long phone, float salary, String domain, String
publication)
{
super(staffid, name, phone, salary);
this.domain=domain;
this.publication=publication;
}
void display()
{
System.out.println(staffid +"\t\t"+ name+"\t\t"+ phone+"\t"+ salary+"\t"+
domain+"\t"+ publication );
}
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 12
Design and Analysis of Algorithm Laboratory
}
class Technical extends Staff
{
String skills;
Technical(int staffid, String name, long phone, float salary, String skills)
{
super(staffid, name, phone, salary);
this.skills=skills;
}
void display()
{
System.out.println(staffid +"\t\t"+ name+"\t\t"+ phone+"\t"+ salary+"\t"+
skills);
}
}
class Contract extends Staff
{
int period;
Contract(int staffid, String name, long phone, float salary, int period)
{
super(staffid, name, phone, salary);
this.period=period;
}
void display()
{
System.out.println(staffid +"\t\t"+ name+"\t\t"+ phone+"\t"+ salary+"\t"+
period);
}
}
public class StaffDetails
{
public static void main(String argrs[]) throws IOException
{
Staff s[]=new Staff[10];
boolean yes=true;
int choice;
Scanner scn=new Scanner(System.in);
do
{
System.out.println("1).Teaching\n2).Technical\n3).Contract\n4).Exit\n\nEnt
er Choice");
choice = scn.nextInt();
switch(choice)
{
case 1:System.out.println("Enter number of teaching staff details");
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 13
Design and Analysis of Algorithm Laboratory
int n=scn.nextInt();
System.out.println("Enter Teaching Staff Details: ID Name
Phone Salary Domain Publication");
for(int i=0;i<n;i++)
{
int id=scn.nextInt();
String name=scn.next();
long phone=scn.nextLong();
float sal=scn.nextFloat();
String domain=scn.next();
String publ=scn.next();
s[i]=new Teaching(id,name,phone,sal,domain,publ);
}
System.out.println("Staff
ID\tName\tPhone\tSalary\tDomain\tPublication");
for(int i=0;i<n;i++)
{
((Teaching) s[i]).display();
}
break;
case 2: System.out.println("Enter number of Technical Staff
Details");
int t=scn.nextInt();
System.out.println("Enter Technical Staff Details: ID Name
Phone Salary Skill");
for(int i=0;i<t;i++)
{
int id=scn.nextInt();
String name=scn.next();
long phone=scn.nextLong();
float sal=scn.nextFloat();
String skill=scn.next();
s[i]=new Technical(id,name,phone,sal,skill);
}
System.out.println("Staff ID\tName\tPhone\tSalary\tSkills");
for(int i=0;i<t;i++)
{
((Technical) s[i]).display();
}
break;
case 3: System.out.println("Enter number of Contract Staff Details");
int c=scn.nextInt();
System.out.println("Enter Contract Staff Details: ID Name
Phone Salary Period");
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 14
Design and Analysis of Algorithm Laboratory
for(int i=0;i<c;i++)
{
int id=scn.nextInt();
String name=scn.next();
long phone=scn.nextLong();
float sal=scn.nextFloat();
int period=scn.nextInt();
s[i]=new Contract(id,name,phone,sal,period);
}
System.out.println("Staff ID\tName\tPhone\tSalary\tPeriod")
for(int i=0;i<c;i++)
{
((Contract) s[i]).display();
}
break;
case 4: scn.close();
System.exit(0);break;
default:System.out.println("Invalid Choice");
}
}while(yes==true);
}
}
Output:
1).Teaching
2).Technical
3).Contract
4).Exit
Enter Choice
1
Enter number of teaching staff details
2
Enter Teaching Staff Details: ID Name Phone Salary Domain Publication
100 AMAR 9999 1000 JAVA PEARSON
200 AJAY 8888 2000 C# PEARSON
StaffID
Name
Phone Salary
Domain
Publication
100
AMAR
9999 1000.0
JAVA
PEARSON
200
AJAY
8888 2000.0
C#
PEARSON
1).Teaching
2).Technical
3).Contract
4).Exit
Enter Choice
2 of CSE, CEC
Dept.
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Enter number of technical staff details
1
Enter Technical Staff Details: ID Name Phone Salary Skill
300 AMAR 8888 4000 C
StaffIDName Phone Salary Skills
Page 15
Design and Analysis of Algorithm Laboratory
Enter Choice
2
Enter number of Technical Staff Details
1
Enter Technical Staff Details: ID Name Phone Salary Skill
300 AMAR 8888 4000 C
StaffID
Name
Phone Salary
Skills
300
AMAR
8888 4000.0
C
1).Teaching
2).Technical
3).Contract
4).Exit
Enter Choice
3
Enter number of Contract Staff Details
1
Enter Contract Staff Details: ID Name Phone Salary Period
400 AJITH 9999 2000 1
StaffID
Name
Phone Salary
Period
400
AJITH
9999 2000.0
1
1).Teaching
2).Technical
3).Contract
4).Exit
Enter Choice
4
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 16
Design and Analysis of Algorithm Laboratory
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.Scanner;
import java.util.StringTokenizer;
public class Customer
{
int Display()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Customer Data");
String data=sc.nextLine();
StringTokenizer st = new StringTokenizer(data, "/");
System.out.print("Customer Data is ");
while(st.hasMoreTokens())
{
String val = st.nextToken();
System.out.print(val);
if(st.countTokens()!=0)
System.out.print(","+" ");
}
sc.close();
return 0;
}
public static void main(String[] args)
{
Customer c=new Customer();
c.Display();
}
}
Output:
Enter Customer Data
Abhishek, 25/07/1986
Customer Data is Abhishek, 25, 07, 1986
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 17
Design and Analysis of Algorithm Laboratory
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.Scanner;
public class Arithmetic
{
Arithmetic()
{
int a,b,c;
Scanner sc=new Scanner(System.in);
try
{
System.out.println("Enter the value of a");
a=sc.nextInt();
System.out.println("Enter the value of b");
b=sc.nextInt();
sc.close();
if(b==0)
throw new ArithmeticException(" Divide by Zero Error");
c=a/b;
System.out.println("value of a is: "+a);
System.out.println("value of b is: "+b);
System.out.println("a/b is: "+c);
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
}
public static void main(String srgs[])
{
new Arithmetic();
}
}
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 18
Design and Analysis of Algorithm Laboratory
Output:
Enter the value of a
3
Enter the value of b
2
value of a is: 3
value of b is: 2
a/b is: 1
Enter the value of a
3
Enter the value of b
0
java.lang.ArithmeticException: Divide by Zero Error
at adaprograms.Arithmetic.<init>(Arithmetic.java:18)
at adaprograms.Arithmetic.main(Arithmetic.java:31)
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 19
Design and Analysis of Algorithm Laboratory
b. Write a Java program that implements a multi-thread application that has three
threads. First thread generates a random integer for every 1 second; second thread
computes the square of the number and prints; third thread will print the value of
cube of the number.
import java.util.Random;
class Square implements Runnable
{
public int x;
public Square(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Square of " + x + " is: " + x * x);
}
}
class Cube implements Runnable
{
public int x;
public Cube(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Cube of " + x + " is: " + x * x * x);
}
}
class JavaThread extends Thread
{
public void run()
{
int num = 0;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)
{
Thread.sleep(1000);
System.out.println("--------------------------------------");
num = r.nextInt(10);
System.out.println("Random Number Generated is " + num);
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 20
Design and Analysis of Algorithm Laboratory
Thread t1 = new Thread(new Square(num));
t1.start();
Thread t2 = new Thread(new Cube(num));
t2.start();
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class MultiThread
{
public static void main(String args[])
{
JavaThread j=new JavaThread();
j.start();
}
}
Output:
-------------------------------------Random Number Generated is 9
Square of 9 is: 81
Cube of 9 is: 729
-------------------------------------Random Number Generated is 6
Square of 6 is: 36
Cube of 6 is: 216
-------------------------------------Random Number Generated is 2
Square of 2 is: 4
Cube of 2 is: 8
-------------------------------------Random Number Generated is 5
Square of 5 is: 25
Cube of 5 is: 125
-------------------------------------Random Number Generated is 4
Square of 4 is: 16
Cube of 4 is: 64
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 21
Design and Analysis of Algorithm Laboratory
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.util.Random;
import java.util.Scanner;
/** Class QuickSort **/
public class QuickSort
{
/** Quick Sort function **/
public static void sort(int[] arr)
{
quickSort(arr, 0, arr.length - 1);
}
/** Quick sort function **/
public static void quickSort(int arr[], int low, int high)
{
int i = low, j = high;
int temp;
int pivot = arr[low];
/** partition **/
while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{
/** swap **/
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
/** recursively sort lower half **/
if (low < j)
quickSort(arr, low, j);
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 22
Design and Analysis of Algorithm Laboratory
/** recursively sort upper half **/
if (i < high)
quickSort(arr, i, high);
}
/** Main method **/
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Quick Sort Test\n");
int i;
/** Accept number of elements **/
System.out.println("Random Numbers generated are: ");
Random r=new Random();
int[] arr=new int[10];
for(i=0;i<10;i++)
{
arr[i]=r.nextInt(10000);
System.out.println(arr[i]);
}
/** Call method sort **/
long startTime = System.nanoTime();
sort(arr);
double endTime = System.nanoTime();
double duration = (endTime - startTime);
/** Print sorted Array **/
System.out.println("\nElements after sorting ");
for (i = 0; i < 10; i++)
System.out.print(arr[i]+" ");
System.out.println();
double milliseconds=duration/1000000;
System.out.println("Total Time taken to sort the
"+milliseconds+" MilliSeconds");
scan.close();
}
numbers
is:
}
Output:
Quick Sort Test
Random Numbers generated are:
9811 8613 5565 4860 3580
7293
1014
9565
424
2456
Elements after sorting
424 1014 2456 3580 4860 5565 7293 8613 9565 9811
Total Time taken to sort the numbers is: 0.02415 MilliSeconds
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 23
Design and Analysis of Algorithm Laboratory
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.util.Random;
import java.util.Scanner;
/* Class MergeSort */
public class MergeSort
{
/* Merge Sort function */
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
// recursively sort
sort(a, low, mid);
sort(a, mid, high);
// merge two sorted subarrays
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}
/* Main method */
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Merge Sort Test\n");
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 24
Design and Analysis of Algorithm Laboratory
int i;
System.out.println("Random Numbers generated are: ");
Random r=new Random();
int[] arr=new int[10];
for(i=0;i<10;i++)
{
arr[i]=r.nextInt(10000);
System.out.println(arr[i]);
}
/* Call method sort */
long startTime = System.nanoTime();
sort(arr, 0, 10);
double endTime = System.nanoTime();
double duration = (endTime - startTime);
/* Print sorted Array */
System.out.println("\nElements after sorting ");
for (i = 0; i < 10; i++)
System.out.print(arr[i]+" ");
System.out.println();
double milliseconds=duration/1000000;
System.out.println("Total Time taken to sort the
"+milliseconds+" MilliSeconds");
scan.close();
numbers
is:
}
}
Output:
Merge Sort Test
Random Numbers generated are:
2740
3735
7949
9666
6436
9833
8368
7945
2957
7874
Elements after sorting
2740 2957 3735 6436 7874 7945 7949 8368 9666 9833
Total Time taken to sort the numbers is: 0.02415 MilliSeconds
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 25
Design and Analysis of Algorithm Laboratory
6. Implement in Java, the 0/1 Knapsack problem using:
a. Dynamic Programming method
import java.util.Scanner;
public class KnapsackDynamicProg
{
static int max(int a, int b)
{
return (a > b)? a : b;
}
static int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int [][]K = new int[n+1][W+1];
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
else
K[i][w] = K[i-1][w];
}
}
return K[n][W];
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of items: ");
int n = sc.nextInt();
System.out.println("Enter the items weights: ");
int []wt = new int[n];
for(int i=0; i<n; i++)
wt[i] = sc.nextInt();
System.out.println("Enter the items values: ");
int []val = new int[n];
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 26
Design and Analysis of Algorithm Laboratory
for(int i=0; i<n; i++)
val[i] = sc.nextInt();
System.out.println("Enter the maximum capacity: ");
int W = sc.nextInt();
System.out.println("The maximum value that can be put in a knapsack of capacity W
is: " + knapSack(W, wt, val, n));
sc.close();
}
}
Output:
Enter the number of items:
4
Enter the items weights:
1
3
2
4
Enter the items values:
2
3
1
4
Enter the maximum capacity:
5
The maximum value that can be put in a knapsack of capacity W is: 6
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 27
Design and Analysis of Algorithm Laboratory
b. 0/1 Knapsack problem using Greedy method
import java.util.Scanner;
public class Knapsack_Greedy
{
void knapsack(int n, float weight[], float value[], float W)
{
float x[]=new float[20], tp= 0;
int i, u;
u=(int) W;
for (i=0;i< n;i++)
x[i]= 0;
for (i=0;i< n;i++)
{
if(weight[i]>u)
break;
else
{
x[i]=1;
tp= tp+value[i];
u=(int) (u-weight[i]);
}
}
if(i< n)
x[i]=u/weight[i];
tp= tp + (x[i]*value[i]);
System.out.println("\n------------------------------------------------");
System.out.print("\nweight | ");
for(i=0;i< n;i++)
{
System.out.print(weight[i]+"\t");
}
System.out.print("\nvalue | ");
for(i=0;i< n;i++)
{
System.out.print(value[i]+"\t");
}
System.out.print("\n x | ");
for(i=0;i< n;i++)
{
System.out.print(x[i]+"\t");
}
System.out.println("\n------------------------------------------------");
System.out.println("\n Maximum value that knapsack carry is:" +tp);
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 28
Design and Analysis of Algorithm Laboratory
System.out.println("\n------------------------------------------------");
}
public static void main(String args[])
{
float weight[]=new float[20], value[]=new float[20], W;
int n, i ,j;
float ratio[]=new float[20], temp;
System.out.println("\n------------------------------------------------");
System.out.println("\n
KNAPSACK PROBLEM USING GREEDY
APPROACH ");
System.out.println("\n------------------------------------------------");
Scanner s=new Scanner(System.in);
System.out.println("\n Enter number of Objects you want:");
n=s.nextInt();
System.out.println("\n------Enter the weights and values of each object-------");
for (i=0; i< n; i++)
{
System.out.println("\nEnter weight and value for object:" +(i+1));
weight[i]=s.nextFloat();
value[i]=s.nextFloat();
}
System.out.println("\nEnter the capacity of knapsack:");
W=s.nextFloat();
for (i=0; i< n; i++)
{
ratio[i]=value[i]/weight[i];
}
for(i=0; i< n; i++)
{
for(j=i+1;j< n; j++)
{
if(ratio[i]< ratio[j])
{
temp= ratio[j];
ratio[j]= ratio[i];
ratio[i]= temp;
temp= weight[j];
weight[j]= weight[i];
weight[i]= temp;
temp= value[j];
value[j]= value[i];
value[i]= temp;
}
}
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 29
Design and Analysis of Algorithm Laboratory
}
Knapsack_Greedy k=new Knapsack_Greedy();
k.knapsack(n, weight, value, W);
s.close();
}
}
Output:
------------------------------------------------------------------------------KNAPSACK PROBLEM USING GREEDY APPROACH
------------------------------------------------------------------------------Enter number of Objects you want:
4
------Enter the weights and values of each object-------Enter weight and value for object: 1
23
Enter weight and value for object: 2
13
Enter weight and value for object: 3
24
Enter weight and value for object: 4
34
Enter the capacity of knapsack:
6
-----------------------------------------------weight | 1.0 2.0
2.0
3.0
value | 3.0 4.0
3.0
4.0
x
| 1.0 1.0
1.0
0.33333334
-----------------------------------------------Maximum value that knapsack carry is: 11.333333
-----------------------------------------------Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 30
Design and Analysis of Algorithm Laboratory
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.*;
public class Dijkstra
{
public int distance[] = new int[10];
public int cost[][] = new int[10][10];
public void calc(int n,int s)
{
int flag[] = new int[n+1];
int i,minpos=1,k,c,minimum;
for(i=1;i<=n;i++)
{
flag[i]=0;
this.distance[i]=this.cost[s][i];
}
c=2;
while(c<=n)
{
minimum=99;
for(k=1;k<=n;k++)
{
if(this.distance[k]<minimum && flag[k]!=1)
{
minimum=this.distance[i];
minpos=k;
}
}
flag[minpos]=1;
c++;
for(k=1;k<=n;k++)
{
if(this.distance[minpos]+this.cost[minpos][k] < this.distance[k] &&
flag[k]!=1 )
this.distance[k]=this.distance[minpos]+this.cost[minpos][k];
}
}
}
public static void main(String args[])
{
int nodes,source,i,j;
Scanner in = new Scanner(System.in);
System.out.println("Enter the Number of Nodes \n");
nodes = in.nextInt();
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 31
Design and Analysis of Algorithm Laboratory
Dijkstra d = new Dijkstra();
System.out.println("Enter the Cost Matrix Weights: \n");
for(i=1;i<=nodes;i++)
for(j=1;j<=nodes;j++)
{
d.cost[i][j]=in.nextInt();
if(d.cost[i][j]==0)
d.cost[i][j]=999;
}
System.out.println("Enter the Source Vertex :\n");
source=in.nextInt();
d.calc(nodes,source);
System.out.println("The Shortest Path from Source "+source+" to all other
vertices are : \n");
for(i=1;i<=nodes;i++)
if(i!=source)
System.out.println("source :"+source+"\t destination :"+i+"\t
MinCost is :"+d.distance[i]+"\t");
}
}
Output:
Enter the Number of Nodes
5
Enter the Cost Matrix Weights:
09653
00000
02040
00000
00000
Enter the Source Vertex:
1
The Shortest Path from Source 1 to all other vertices are:
source :1
source :1
source :1
source :1
destination :2
destination :3
destination :4
destination :5
Dept. of CSE, CEC
MinCost is :9
MinCost is :6
MinCost is :5
MinCost is :3
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 32
Design and Analysis of Algorithm Laboratory
8. Find Minimum Cost Spanning Tree of a given undirected graph using
a. Kruskal's algorithm
import java.util.Scanner;
public class Kruskal
{
static int path[];
static int n, m, mincost, i, j;
public static void main (String args[]) throws Exception
{
Scanner s=new Scanner(System.in);
// Creating graph of 'n' vertices & 'm' edges
System.out.print("Enter the number of vertices in the graph: ");
n = s.nextInt();
System.out.print("Enter the number of edges in the graph: ");
m = s.nextInt();
path = new int[n+1];
Edge e[] = new Edge[m];
Edge t = new Edge();
for (i=0; i<m; i++)
{
e[i] = new Edge();
System.out.println("Enter 2 vertices and weight of edge: ");
System.out.print("First vertex: ");
e[i].u = s.nextInt();
System.out.print("Second vertex: ");
e[i].v = s.nextInt();
System.out.print("Weight: ");
e[i].wt = s.nextInt();
}
// Sorting the edges in ascending order of weights
for (i=0; i<=m-1; i++)
{
for (j=0; j<m-i-1; j++)
{
if (e[j].wt > e[j+1].wt)
{
t = e[j];
e[j] = e[j+1];
e[j+1] = t;
}
}
}
// Initializing the path array
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 33
Design and Analysis of Algorithm Laboratory
for (i=1; i<=n; i++)
{
path[i] = 0;
}
// Counts the number of edges selected in the tree
i = 0;
// Counts the number of edges selected or discarded
j = 0;
mincost = 0;
System.out.println();
while ((i!=n-1) && (j!=m))
{
System.out.print("Edge ("+ e[j].u + ", " + e[j].v + ") "
+ "with weight " + e[j].wt + " ");
if (checkCycle(e[j]))
{
mincost = mincost + e[j].wt;
i++;
System.out.println("is selected");
}
else
{
System.out.println("is discarded");
}
j++;
}
if (i!=n-1)
{
System.out.println("Minimum spanning tree cannot be formed ");
}
s.close();
}
public static boolean checkCycle(Edge e)
{
int u = e.u, v = e.v;
while (path[u] > 0)
u = path[u];
while (path[v] > 0)
v = path[v];
if (u != v)
{
path[u] = v;
return true;
}
return false;
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 34
Design and Analysis of Algorithm Laboratory
}
static class Edge
{
int u, v, wt;
}
}
Output:
Enter the number of vertices in the graph: 4
Enter the number of edges in the graph: 5
Enter 2 vertices and weight of edge:
First vertex: 0
Second vertex: 1
Weight: 10
Enter 2 vertices and weight of edge:
First vertex: 0
Second vertex: 2
Weight: 6
Enter 2 vertices and weight of edge:
First vertex: 0
Second vertex: 3
Weight: 5
Enter 2 vertices and weight of edge:
First vertex: 1
Second vertex: 3
Weight: 15
Enter 2 vertices and weight of edge:
First vertex: 2
Second vertex: 3
Weight: 4
Edge (2, 3) with weight 4 is selected
Edge (0, 3) with weight 5 is selected
Edge (0, 2) with weight 6 is discarded
Edge (0, 1) with weight 10 is selected
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 35
Design and Analysis of Algorithm Laboratory
b. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s
algorithm.
import java.util.Scanner;
public class Prims
{
public int isVisited[] = new int[15];
public int cost[][] = new int[10][10];
public int minimum_cost;
public void calc(int n)
{
int flag[] = new int[n+1];
int i,j,min=999,num_edges=1,a=1,b=1,minpos_i=1,minpos_j=1;
while(num_edges < n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(this.cost[i][j]<min)
if(this.isVisited[i]!=0)
{
min=this.cost[i][j];
a=minpos_i=i;
b=minpos_j=j;
}
if(this.isVisited[minpos_i]==0 || this.isVisited[minpos_j]==0)
{
System.out.println("Edge Number \t"+num_edges+"\t from
Vertex \t"+a+"\t to Vertex \t"+b+"-mincost:"+min+" \n");
this.minimum_cost=this.minimum_cost+min;
num_edges=num_edges+1;
this.isVisited[b]=1;
}
this.cost[a][b]=this.cost[b][a]=999;
}
System.out.println("Minimum Cost= "+minimum_cost);
}
public static void main(String args[])
{
int nodes,i,j;
Scanner in = new Scanner(System.in);
System.out.println("Enter the Number of Nodes \n");
nodes = in.nextInt();
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 36
Design and Analysis of Algorithm Laboratory
Prims p = new Prims();
System.out.println("Enter the Cost Matrix Weights : \n");
for(i=1;i<=nodes;i++)
for(j=1;j<=nodes;j++)
{
p.cost[i][j]=in.nextInt();
if(p.cost[i][j]==0)
p.cost[i][j]=999;
}
p.isVisited[1]=1; // Initialization
p.calc(nodes);
}
}
.
Output:
Enter the Number of Nodes
5
Enter the Cost Matrix Weights :
02060
20385
03007
68009
05790
Edge Number 1
from Vertex 1
to Vertex
2-mincost: 2
Edge Number 2
from Vertex 2
to Vertex
3-mincost: 3
Edge Number 3
from Vertex 2
to Vertex
5-mincost: 5
Edge Number 4
from Vertex 1
to Vertex
4-mincost: 6
Minimum Cost= 16
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 37
Design and Analysis of Algorithm Laboratory
9. Write Java programs to
a. Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
class Floyd
{
final static int INF = 99999, V = 4;
void floydWarshall(int graph[][])
{
int dist[][] = new int[V][V];
int i, j, k;
/* Initialize the solution matrix same as input graph matrix.
Or we can say the initial values of shortest distances
are based on shortest paths considering no intermediate
vertex. */
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
/* Add all vertices one by one to the set of intermediate
vertices.
---> Before start of a iteration, we have shortest
distances between all pairs of vertices such that
the shortest distances consider only the vertices in
set {0, 1, 2, .. k-1} as intermediate vertices.
----> After the end of a iteration, vertex no. k is added
to the set of intermediate vertices and the set
becomes {0, 1, 2, .. k} */
for (k = 0; k < V; k++)
{
// Pick all vertices as source one by one
for (i = 0; i < V; i++)
{
// Pick all vertices as destination for the
// above picked source
for (j = 0; j < V; j++)
{
// If vertex k is on the shortest path from
// i to j, then update the value of dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
// Print the shortest distance matrix
printSolution(dist);
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 38
Design and Analysis of Algorithm Laboratory
}
void printSolution(int dist[][])
{
System.out.println("Following matrix shows the shortest "+
"distances between every pair of vertices");
for (int i=0; i<V; ++i)
{
for (int j=0; j<V; ++j)
{
if (dist[i][j]==INF)
System.out.print("INF ");
else
System.out.print(dist[i][j]+" ");
}
System.out.println();
}
}
// Driver program to test above function
public static void main (String[] args)
{
/* Let us create the following weighted graph 10
(0)------->(3)
|
/|\
5|
|
|
|1
\|/
|
(1)------->(2)
3
*/
int graph[][] = { {0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
Floyd a = new Floyd();
// Print the solution
a.floydWarshall(graph);
}
}
Output:
Following matrix shows the shortest distances between every pair of vertices
0 5 8
9
INF 0 3
4
INF INF
0 CEC
1
Dept.
of CSE,
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
INF INF INF 0
Page 39
Design and Analysis of Algorithm Laboratory
b. Implement Travelling Sales Person problem using Dynamic programming.
import java.util.*;
class TSPExp
{
int weight[][],n,tour[],finalCost;
final int INF=1000;
public 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();
s.close();
}
public int COST(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++)
{
int k=0;//initialise new set
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 40
Design and Analysis of Algorithm Laboratory
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 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();
}
public void constructTour()
{
int previousSet[]=new int[n-1];
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 41
Design and Analysis of Algorithm Laboratory
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[])
{
new TSPExp();
}
}
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 42
Design and Analysis of Algorithm Laboratory
Output:
Enter no. of nodes:=>
5
Enter weight of 1 to 2:=>4
Enter weight of 1 to 3:=>6
Enter weight of 1 to 4:=>3
Enter weight of 1 to 5:=>7
Enter weight of 2 to 1:=>3
Enter weight of 2 to 3:=>1
Enter weight of 2 to 4:=>7
Enter weight of 2 to 5:=>4
Enter weight of 3 to 1:=>7
Enter weight of 3 to 2:=>4
Enter weight of 3 to 4:=>3
Enter weight of 3 to 5:=>6
Enter weight of 4 to 1:=>8
Enter weight of 4 to 2:=>5
Enter weight of 4 to 3:=>3
Enter weight of 4 to 5:=>2
Enter weight of 5 to 1:=>4
Enter weight of 5 to 2:=>3
Enter weight of 5 to 3:=>2
Enter weight of 5 to 4:=>1
Starting node assumed to be node 1.
The tour is 1-2-3-4-5-1
The final cost is 14
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 43
Design and Analysis of Algorithm Laboratory
10.
a. 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;
public class Subset
{
static int s[]=new int[10] ;
int x[]=new int[10];
static int d;
void sumofsub ( int m , int k , int r )
{
int i=1 ;
x[k]=1;
if ( ( m + s[k] ) == d )
{
System.out.print("Subset:");
for ( i = 1 ; i <= k ; i++ )
if ( x[i] == 1 )
System.out.print(s[i]+"\t");
System.out.println("\n") ;
}
else
if ( m + s[k] + s[k+1] <= d )
sumofsub ( m + s[k] , k + 1 , r - s[k] ) ;
if ( ( m + r - s[k] >= d ) && ( m + s[k+1] <=d ) )
{
x[k] = 0;
sumofsub ( m , k + 1 , r - s[k] ) ;
}
}
public static void main (String args[])
{
Subset sb=new Subset();
int n , sum = 0 ;
int i ;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the set : " ) ;
n=sc.nextInt();
System.out.println("Enter the set in increasing order:" ) ;
for ( i = 1 ; i <= n ; i++ )
s[i]=sc.nextInt();
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 44
Design and Analysis of Algorithm Laboratory
System.out.print("Enter the value of d :") ;
d=sc.nextInt();
for ( i = 1 ; i <= n ; i++ )
sum = sum + s[i] ;
if ( sum < d || s[1] > d )
System.out.println("No subset possible : ") ;
else
sb.sumofsub ( 0 , 1 , sum ) ;
sc.close();
}
}
Output:
Enter the size of the set: 5
Enter the set in increasing order:
12345
Enter the value of d: 5
Subset: 1
4
Subset: 2
3
Subset: 5
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 45
Design and Analysis of Algorithm Laboratory
b. Design and implement the presence of Hamiltonian Cycle in an undirected Graph G
of n vertices.
public class HamiltonianCycle
{
final int V = 5;
int path[];
/* A utility function to check if the vertex v can be
added at index 'pos'in the Hamiltonian Cycle
constructed so far (stored in 'path[]') */
boolean isSafe(int v, int graph[][], int path[], int pos)
{
/* Check if this vertex is an adjacent vertex of
the previously added vertex. */
if (graph[path[pos - 1]][v] == 0)
return false;
/* Check if the vertex has already been included.
This step can be optimized by creating an array
of size V */
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
return true;
}
/* A recursive utility function to solve Hamiltonian cycle problem */
boolean hamCycleUtil(int graph[][], int path[], int pos)
{
/* base case: If all vertices are included in Hamiltonian Cycle */
if (pos == V)
{
// And if there is an edge from the last included
// vertex to the first vertex
if (graph[path[pos - 1]][path[0]] == 1)
return true;
else
return false;
}
// Try different vertices as a next candidate in
// Hamiltonian Cycle. We don't try for 0 as we
// included 0 as starting point in in hamCycle()
for (int v = 0; v < V; v++)
{
/* Check if this vertex can be added to Hamiltonian
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 46
Design and Analysis of Algorithm Laboratory
Cycle */
if (isSafe(v, graph, path, pos))
{
path[pos] = v;
/* recur to construct rest of the path */
if (hamCycleUtil(graph, path, pos + 1) == true)
return true;
/* If adding vertex v doesn't lead to a solution,
then remove it */
path[pos] = -1;
}
}
/* If no vertex can be added to Hamiltonian Cycle
constructed so far, then return false */
return false;
}
/* This function solves the Hamiltonian Cycle problem using
Backtracking. It mainly uses hamCycleUtil() to solve the
problem. It returns false if there is no Hamiltonian Cycle
possible, otherwise return true and prints the path.
Please note that there may be more than one solutions,
this function prints one of the feasible solutions. */
int hamCycle(int graph[][])
{
path = new int[V];
for (int i = 0; i < V; i++)
path[i] = -1;
/* Let us put vertex 0 as the first vertex in the path.
If there is a Hamiltonian Cycle, then the path can be
started from any point of the cycle as the graph is
undirected */
path[0] = 0;
if (hamCycleUtil(graph, path, 1) == false)
{
System.out.println("\nSolution does not exist");
return 0;
}
printSolution(path);
return 1;
}
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 47
Design and Analysis of Algorithm Laboratory
/* A utility function to print solution */
void printSolution(int path[])
{
System.out.println("Solution Exists: Following" +
" is one Hamiltonian Cycle");
for (int i = 0; i < V; i++)
System.out.print(" " + path[i] + " ");
// Let us print the first vertex again to show the
// complete cycle
System.out.println(" " + path[0] + " ");
}
// driver program to test above function
public static void main(String args[])
{
HamiltonianCycle hamiltonian =
new HamiltonianCycle();
/* Let us create the following graph
(0)--(1)--(2)
| /\ |
| / \ |
|/ \|
(3)-------(4) */
int graph1[][] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};
// Print the solution
hamiltonian.hamCycle(graph1);
/* Let us create the following graph
(0)--(1)--(2)
| /\ |
| / \ |
|/ \|
(3)
(4) */
int graph2[][] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 48
Design and Analysis of Algorithm Laboratory
};
// Print the solution
hamiltonian.hamCycle(graph2);
}
}
Output:
Solution Exists: Following is one Hamiltonian Cycle
012430
Solution does not exist
Dept. of CSE, CEC
Prepared By: Prof. Abhishek S. Rao & Prof. Santosh
Page 49