You are on page 1of 44

INSTITUTIONAL MISSION AND VISION

MISSION:
To foster an intellectual and ethical environment in which both skill and spirit will thrive so as to
impart high quality education, training, and service with an international outlook. To create and
develop technocrats and business leaders who will strive to improve the quality of life.

VISION:
To become a world-class center in providing globally relevant higher education in the field of
management, technology and applied science embedded with human values.

DEPARTMENT VISION AND MISSION

MISSION:

Don Bosco Bangalore, Department of Computer Science and Engineering would like to nurture the
development of skill sets among the students in the area of software engineering, computer
networking, database, computer graphics, operating systems, artificial intelligence, numerical and
symbolic computation with the collaborative efforts of participants and industry.

VISION:

Don Bosco Bangalore, Department of Computer Science and Engineering looks forward to be a
quality centre of computation by imparting knowledge on various algorithms and data structures,
programming methodology and languages with an orientation of computer architecture as per the
standards of the industry with cohesive efforts of its students and staffs.
PROGRAMME EDUCATIONAL OBJECTIVES AND PROGRAMME OUTCOMES

PROGRAMME EDUCATIONAL OBJECTIVES:


Program Educational Objective 1: To impart education to enable the students to
become graduates in Computer Science and Engineering and also to be able to pursue for
higher studies or to join the work force.
Program Educational Objective 2: To enable them to acquire a good knowledge in science,
mathematics, general engineering and technology to be competent to apply the same.
Program Educational Objective 3: To give an exposure to other related fields of
engineering and technology in addition to their chosen field for an effective working.
Program Educational Objective 4: To make them function in a true professional way
imbibing spiritual, ethical and moral values and to work for the benefit of the community at
large.
Program Educational Objective 5: To motivate them to incessantly keep abreast with the
developments in their chosen and related fields through continuous learning to remain
effective in their vocation.

PROGRAMME OUTCOMES:
a) An ability to apply knowledge of mathematics, science, and engineering.
b) An ability to design and conduct experiments, as well as to analyze and interpret data.
c) An ability to design a system, component, or process to meet desired needs within realistic
constraints such as economic, environmental, social, political, ethical, health and safety,
manufacturability, and sustainability.
d) An ability to function on multidisciplinary teams.
e) An ability to identify, formulates, and solves (complex) engineering problems.
f) An understanding of professional and ethical responsibility.
g) An ability to communicate effectively
h) The broad education necessary to understand the impact of engineering solutions
in a global,economic, environmental, and societal context.
i) Recognition of the need for, and an ability to engage in life-long learning.
j) Knowledge of contemporary issues,
k) An ability to use the techniques, skills, and modern engineering tools necessary for
engineering practice.
l) An ability to understand discrete mathematics and apply for the solution for the problem
Design and Analysis of Algorithm Lab

Contents
Sl.No. Program Page No.
1 Program to
a) Create n Student objects and print the USN, Name, Branch, and Phone of 1
these objects
b) Implement the Stack using arrays 3
2 Program to
a) Design super class and extend class 6
b) Read customer data as <name, dd/mm/yyyy> and display as <name, dd, 8
mm, yyyy> using StringTokenizer class
3 Program to
(a) Read two integers a and b and compute a/b 9
(b) Implement a multi-thread application that hashtree threads 10
4 Program to sort a given set of n integer elements using Quick Sort method and 12
compute its time complexity
5 Program to sort a given set of n integer elements using Merge Sort method and 14
compute its time complexity
6 Program that implements, the 0/1 Knapsack problem using
(a) Dynamic Programming method 16
(b) Greedy method 19
7 Program to find shortest paths to other vertices using Dijkstra's algorithm. 22
8 Program to find Minimum Cost Spanning Tree of a given undirected graph using
(a) Kruskal's algorithm 25
(b) Prim's algorithm 27
9 Program to
a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm 30
b) Implement Travelling Sales Person problem using Dynamic programming 32
10 Design and implementation of
a) Subset sum Problem 34
b) Hamiltonian cycle in an undirected graph 37

Department of CSE,DBIT, Bengaluru


Design and Analysis of Algorithm Lab

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 IA Marks 20
Number of Lecture Hours/Week 01 I + 02 P Exam Marks 80
Total Number of Lecture Hours 40 Exam Hours 03
CREDITS – 02
Course objectives:
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.
Description
Design, develop, and implement the specified algorithms for the following problems using
Java language under LINUX /Windows environment. Netbeans/Eclipse IDE tool can be used for
development and demonstration.
Experiments
1 A.Create a Java class called Student with the following details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create n Student objects and print the USN, Name, Branch, and Phone of
these objects with suitable headings.
1 B. Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display()
methods to demonstrate its working.

2 A. Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this class
by writing three subclasses namely Teaching (domain, publications), Technical (skills), and Contract
(period). Write a Java program to read and display at least 3 sttff objects of all three categories.
2 B. Write a Java class called Customer to store their name and date_of_birth. The date_of_birth
format should be dd/mm/yyyy. Write methods to read customer data as <name, dd/mm/yyyy> and
display as <name, dd, mm, yyyy> using StringTokenizer class considering the delimiter character as
“/”.

3 A. Write a Java program to read two integers t and b. Compute t/b and print, when b is not zero.
Raise an exception when b is equal to zero.
B. Write a Java program that implements a multi-thread application that hashtree threads. First thread
generates a random integer for every 1 second; second thread computes the square of the number and
prints; third thread will print the value of cube of the number.

Department of CSE,DBIT, Bengaluru


Design and Analysis of Algorithm Lab
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 and-conquer
conquer method works along
with its time complexity analysis: worst case, average case and best case.

5. Sort a given set of n integer elements using Merge Sort method and compute its time complexity.
Run the program for varied values of n > 5000, and record the time taken to sort. Plot a graph of the
time taken versus n on graph sheet. The elements can be read from a file or can be generated using the
random number generator. Demonstrate using Java how the divide and conquer method works along
with its time complexity analysis: worst case, average case and best case.

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

7. From a given vertex in a weighted connected graph, find shortest paths to other vertices using
Dijkstra's algorithm.. Write the program in Java.

8. Find Minimum Cost Spanning Tree of a given undirected graph using


(a) Kruskal's algorithm
(b) Prim's algorithm.. Implement the program in Java language.

9. Write Java programs to


(a) Implement All-Pairs
Pairs Shortest Paths problem using Floyd's algorithm.
(b) Implement Travelling Sales Person problem using Dynamic programming.

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.
10 B. Design and implement the presence of Hamiltonian Cycle in an undirected Graph G of n
vertices.

Department of CSE,DBIT, Bengaluru


Design and Analysis of Algorithm Lab
Course Outcomes:
The students should be able to:
• Design algorithms using appropriate design techniques (brute
(brute-force, greedy, dynamic
programming, etc.)
• Implement a variety of algorithms such as sorting, 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.

Graduate Attributes
• Engineering Knowledge
• Problem Analysis
• Modern Tool Usage
• Conduct Investigations of Complex Problems
• Design/Development of Solutions

Conduction of Practical Examination:


All laboratory experiments (TEN problems) are to be included for practical examination.
Students are allowed to pick one expe
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 part to be made
zero.

Department of CSE,DBIT, Bengaluru


Design and Analysis of Algorithm Lab

/* 1 A. Create a Java class called Student with the following


details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create n Student objects and print the
USN, Name, Branch, and Phone of these objects with suitable
headings.*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package student;
import java.util.Scanner;
/**
*
* @author Studets
*/
public class Student {

public Student(String stuUSN,String stuName,String stuBranch,String stuPhone){


System.out.println("Student USN is:"+stuUSN);
System.out.println("Student Name is:"+stuName);
System.out.println("Student Branch is:"+stuBranch);
System.out.println("Student Phone number is:"+stuPhone);
}
public static void main(String[] args) {
Scanner readInput = new Scanner(System.in);
System.out.println("Enter number of student objects to create");
int numberOfStudents = readInput.nextInt();
for(int i =1;i<=numberOfStudents;i++){
System.out.println("Enter Student USN");
String usn = readInput.next();
System.out.println("Enter Student Name");
String name = readInput.next();
System.out.println("Enter Student Branch");
String branch = readInput.next();
System.out.println("Enter Student Phone");
String phone = readInput.next();
new Student(usn, name,branch, phone);
}

OUTPUT :

Enter USN:-
4SN16CS049
Enter Name:-
SREEHAN
Enter Branch:-
CSE
Enter Phone number:-
9945081055
Student Details
USN Name Branch Phone
4SN16CS049 SREEHAN CSE 9945081055
Design and Analysis of Algorithm Lab
/* 1B. Write a Java program to implement the Stack using arrays.
Write Push(), Pop() and Display() methods to demonstrate its
working.*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackdemo;
import java.util.*;

public class StackDemo


{

int stackArray[], top, arraySize;

public StackDemo(int n)
{
arraySize = n;
stackArray = new int[arraySize];
top = -1;
}

/* Method to check if stack is empty */


public boolean isEmpty()
{
return top == -1;
}

/* Method to check if stack is full */


public boolean isFull()
{
return top == arraySize - 1;
}

/* Method to push an element to the stack */


public void push(int i)
{
if (top + 1 >= arraySize)
{
System.out.println("Stack is full!!");
} else
{
stackArray[++top] = i;
}
}

/* Method to pop an element from the stack */


public void pop()
{
if (top == -1)
1)
{
System.out.println("Stack is Empty!!");
} else
{
System.out.println("Popped element is:" +
stackArray[top--]);
Design and Analysis of Algorithm Lab
}
}

/* Method to display the status of the stack */


public void display()
{
System.out.print("\nStack = ");
if (top == -1)
{
System.out.println("Stack is Empty");
return;
}
for (int i = top; i >= 0; i--)
System.out.print(stackArray[i] + " ");
System.out.println();
}

public static void main(String[] args)


{
Scanner inputData = new Scanner(System.in);
System.out.println("Enter Size of the Stack ");
int n = inputData.nextInt();
StackDemo stk = new StackDemo(n);
char ch;
do {
System.out.println("Please Select following option");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
int choice = inputData.nextInt();
switch (choice)
{
case 1:
System.out.println("Enter integer element to
push");
int element = inputData.nextInt();
stk.push(element);
break;
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
default:
System.out.println("Wrong Entry \n ");
break;
}
System.out.println("\nDo you want to continue (Type y or
n) \n");
ch = inputData.next().charAt(0);
} while (ch == 'Y' || ch == 'y');
}
}
Design and Analysis of Algorithm Lab
OUTPUT:
Enter Your Choice
1.PUSH
2.POP
3.DISPLAY
3
Stack is empty
Enter Your Choice
1.PUSH
2.POP
3.DISPLAY
2
Stack Underflow !
Enter Your Choice
1.PUSH
2.POP
3.DISPLAY
1
Enter Number to be pushed:-
11
Element 11 is pushed into Stack !
Enter Your Choice
1.PUSH
2.POP
3.DISPLAY
1
Enter Number to be pushed:-
33
Element 33 is pushed into Stack !

Enter Your Choice


1.PUSH
2.POP
3.DISPLAY
1
Enter Number to be pushed:-
22
Element 22 is pushed into Stack !
Enter Your Choice
1.PUSH
2.POP
3.DISPLAY
1
Enter Number to be pushed:-
64
Stack Overflow !
Enter Your Choice
1.PUSH
2.POP
3.DISPLAY
Design and Analysis of Algorithm Lab
3
Elements in stack :
11
33
22
Enter Your Choice
1.PUSH
2.POP
3.DISPLAY
2
Pop operation is successfull ! and popped element is :22
Enter Your Choice
1.PUSH
2.POP
3.DISPLAY
2
Pop operation is successfull ! and popped element is :33
Enter Your Choice
1.PUSH
2.POP
3.DISPLAY
2
Pop operation is successfull ! and popped element is :11
Enter Your Choice
1.PUSH
2.POP
3.DISPLAY
2
Stack Underflow !
Design and Analysis of Algorithm Lab
/* 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 at
least 3 staff objects of all three categories. */

class Staff{
private int StaffId;
private String Name;
private String Phone;
private long Salary;
public Staff(int staffId,String name,String phone,
phone,long
long salary){
StaffId = staffId;
Name = name;
Phone = phone;
Salary = salary;
}

public void Display(){


System.out.print("\
\t"+StaffId+"\t"+Name+"\t"+Phone+"\t"+Salary);
t"+Salary);
}
}

class Teaching extends Staff{


private String Domain;
private int Publications;
public Teaching(int
int staffId, String name, String phone,
long salary, String domain, int publications){
(staffId, name, phone, salar
super(staffId, salary);
Domain = domain;
Publications = publications;
}

public void Display(){


super.Display();
System.out.print("\t\
\t"+Domain+"\t"+Publications+"\t"+"--"+"\t"+"
t"+"--");
}
}

class Technical extends Staff{


private String Skills;
public Technical(int
int staffId, String name, String phone,
long salary, String skills) {
(staffId, name, phone, salary);
super(staffId,
Skills = skills;
}

public void Display(){


super.Display();
System.out.print("
.print("\t\t--"+"\t\t"+"--"+"\t"+Skills+"\
\t"+"--");
}
}
Design and Analysis of Algorithm Lab

class Contract extends Staff{


private int Period;
public Contract(int
int staffId, String name, String phone,
long salary, int period) {
(staffId, name, phone, salary);
super(staffId,
.Period = period;
this.Period
}

public void Display(){


super.Display();
System.out.print("\t
t\t--"+"\t\t"+"--"+"\t\t"+"--"+"\t\t"+Period);
t"+Period);
}
}

public class Lab2A {


public static void main(String[] args) {
Staff staff[]=new
new Staff[3];
staff[0]=new Teaching(1,"Narendr","271173",90000,"CSE",3);
staff[1]=new Technical(2,"Ara","271172",2000,"Server Admin");
staff[2]=new Contract(3,"Rahul","271174",9000,3);
System.out.println("Staff
.println("Staff ID\t
ID
Name\t\tPhone\t\tSalary
tSalary\t\tDomain\tPublication\tSkills\tPeriod");
tPeriod");
for(int i=0;i<3;i++){
staff[i].Display();
System.out.println();
.println();
}
}
}

OUTPUT :

Staff ID Name Phone Salary Domain Publication Skills Period


1 Naren 271173 90000 CSE 3 -- --
2 Ara 271172 2000 -- -- Server Admin --
3 Rahul 271174 9000 -- -- -- 3
Design and Analysis of Algorithm Lab
/* 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 “/”. */
import java.util.Scanner;
import java.util.StringTokenizer;
tringTokenizer;
class Customer{
private String name;
private String date_of_birth;
public Customer(String name, String date_of_birth) {
super();
this.name = name;
this.date_of_birth = date_of_birth;
}
public Customer (){
}
public void readData
readData(String
(String name, String date_of_birth){
this.name = name;
this.date_of_birth = date_of_birth;
}
public void displayData(){
StringTokenizer st=new
StringTokenizer(this.date_of_birth,"/");
System.out.print(this.name+",");
while(st.hasMoreTokens()){
System.out.print(st.nextToken()+" ");
}
}
}
public class Lab2B {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter Name :
:-");
String name=in.nextLine();
System.out.println("Enter Date of birth:
birth:-");
String date=in.next();
Customer customer=new Customer();
customer.readData(name, date);
customer.displayData();
}

OUTPUT:
Enter Name :-
KALAM
Enter Date of birth:-
19/01/2000
KALAM,19 01 2000
Design and Analysis of Algorithm Lab
/* 3A. Write a Java program to read two integers a and b.
b Compute
a/b and print, when b is not zero. Raise an exception when b is
equal to zero.*/

import java.util.Scanner;
class MyException extends Exception {
public String toString() {
return "Denominator is 0! Division by zero ERROR";
}
}
class Compute {
private int a,b;
public Compute(int a, int b) {
super();
this.a = a;
this.b = b;
}
public void compute_a_by_b() {
try {
if (this.b != 0) {
System.out.println("Result a/b="+(float)1.0*this.a/this.b);
}
else throw new MyException();
} catch (MyException
MyException e) {
System.out.println("Error !!!!: " + e);
}
}
}
public class Lab3A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a ::-");
int a = in.nextInt();
System.out.print("Enter b:
b:-");
int b = in.nextInt();
Compute compute = new Compute(a, b);
compute.compute_a_by_b();
}
}

OUTPUT 1:
Enter a :-2
Enter b:-5
Result a/b=0.4

OUTPUT 2:
Enter a :-2
Enter b:-0
Error !!!!: Denominator is 0! Division by zero ERROR
Design and Analysis of Algorithm Lab
/* 3B. Write a Java program that implements a multi-thread
multi
application that hashtree threads. First thread generates a
random integer for every 1 second; second thread computes the
square of the number and prints; third thread will print the
value of cube of the number.*/

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

class Random_Num_Thread extends Thread {


public void run() {
Random rand;
int i = 0;
do {
rand = new Random();
System.
System.out.print(rand.nextInt(100)+"
.print(rand.nextInt(100)+" ");
i++;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (i < 10);

}
}

class Square_Num extends Thread {


int n;
public void run() {
System.out.println("Square
.println("Square of a Number "+this.n+"
"+ is:"+Math.pow(this
this.n, 2));
}

public Square_Num(int
int a) {
this.n = a;
}
}

class Cube_Num extends Thread {


int n;
public void run() {
System.out.println("\nCube
nCube of a Number "+this.n+"
"+ is:"+Math.pow(this
this.n, 3));
}
public Cube_Num(int a) {
.n = a;
this.n
}
}
public class Lab3B {
public static void main(String[] args) {
Thread thread1 = new Random_Num_Thread();
thread1.start();
Design and Analysis of Algorithm Lab

Thread thread2 = new Square_Num(2);


thread2.start();

Thread thread3 = new Cube_Num(2);


thread3.start();

OUPUT 1:
Square of a Number 2 is :4.0
36
Cube of a Number 2 is :8.0
65 82 26 72 45 90 89 41 3

OUPUT 2:
44
Square of a Number 2 is :4.0
Cube of a Number 2 is :8.0
73 61 69 35 10 66 96 33 76
Design and Analysis of Algorithm Lab
/*4. Sort a given set of n integer elements using the Quicksort
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
along with its time complexity analysis:
worst case, average case and best case.*/

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

public class Lab4 {


public static void main(String[] args) {
int a[]= new int[100000];
[100000];
Scanner in = new Scanner(System.
Scanner(System.in);
long start, end;
.println("*********QUICK SORT PROGRAM
System.out.println("*********QUICK *********");
System.out.println("Enter
.println("Enter the number of elements to be sorted");
int n = in.nextInt();
Random rand= new Random();
for(int i=0;i<n;i++)
a[i]=rand.nextInt(100);
System.out.println(
.println("Array
"Array elements to be sorted are");
for(int i=0; i<n; i++)
System.out.print(a[i]+"
.print(a[i]+" ");
a[n]=999;
start=System.nanoTime
nanoTime();
1);
quicksort(a,0,n-1);
end=System.nanoTime
nanoTime();
System.out.println("
.println("\nThe sorted elements are");
for(int i=0; i<n; i++)
System.out.print(a[
.print(a[i]+" ");
System.out.println("The
.println("The time taken to sort is "+(end
"+(end-start)+"ns");
start)+"ns");
System.out.println("********
.println("******** ******************* *******");
}

static void quicksort(


quicksort(int a[],int p, int q){
int j;
if(p < q){
j=partition(a,p,q); // partition array into parts
quicksort(a,p,j
quicksort(a,p,j-1); // sort left part of array
quicksort(a,j+1,q); // sort right part of array
}
}

static int partition(


partition(int a[],int m, int p){
int v, i, j;
v=a[m]; // first element is pivot element
i=m;
j=p;
Design and Analysis of Algorithm Lab
while(i <= j){
while
while(a[i] <= v)
i++;
while
while(a[j] > v)
j--;
(i < j)
if(i
interchange(a,i,j); //swap the contents
}
a[m] = a[j];
a[j] = v;
return j;
}

static void interchange(int


interchange( a[], int i, int j){
int p;
p = a[i];
a[i] = a[j];
a[j] = p;
}
}

OUTPUT 1:
********** QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
10
Array elements to be sorted are
36 64 13 82 9 19 53 0 72 23
The sorted elements are
0 9 13 19 23 36 53 64 72 82

The time taken to sort is 22970ns


******** *********************** *******

OUTPUT 2:
********** QUICK SORT PROGRAM *********
Enter the number of elements to be sorted
20
Array elements to be sorted are
35 93 25 35 92 97 43 88 92 0 35 57 78 32 59 56 98 4 71 9
The sorted elements are
0 4 9 25 32 35 35 35 43 56 57 59 71 78 88 92 92 93 97 98

The time taken to sort is 31278ns


******** *********************** *******
Design and Analysis of Algorithm Lab
Sort a given set of n integer elements using Merge Sort
/* 5.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;

public class Lab5 {


public static void main(String[] args) {
int a[]= new int[100000];
[100000];
Scanner in = new Scanner(System.in);
Scanner(System.
long start, end;
System.out.println("**********
.println("********** MERGE SORT PROGRAM *********");
System.out.println("Enter
.println("Enter the number of elements to be sorted");
int n = in.nextInt();
Random rand= new Random();
for(int i=0;i<n;i++)
a[i]=rand.nextInt(100);
System.out.println("Array
.println("Array ele
elements
ments to be sorted are");
for(int i=0; i<n; i++)
System.out.print(a[i]+"
.print(a[i]+" ");
start=System.nanoTime
nanoTime();
1);
mergesort(a,0,n-1);
end=System.nanoTime
nanoTime();
System.out.println("
.println("\nThe sorted elements are");
for(int i=0; i<n; i++)
System.out.print(a[i]+"
.print(a[i]+" ");
System.out.println("The
.println("The time taken to sort is "+(end
"+(end-start)+"ns");
start)+"ns");
System.out.println("********
.println("******** ********************** *******");
}
static void mergesort(int
mergesort( a[], int low, int high){
int mid;
if(low < high){
mid = (low+high)/2;
(a, low, mid);
mergesort(a,
(a, mid+1, high);
mergesort(a,
(a, low, mid, high);
merge(a,
}
}
static void merge(int
int a[], int low, int mid, int high){
int i, j, h, k, b[]= new int[100000];
h=low; i=low; j=mid+1;
((h<=mid) && (j<=high)){
while((h<=mid)
(a[h] < a[j]){
if(a[h]
b[i] = a[h]; h=h+1;
}
Design and Analysis of Algorithm Lab
else
{
b[i] = a[j]; j=j+1;
}
i = i+1;
}
if(h > mid){
(k=j; k<=high; k++){
for(k=j;
b[i] = a[k]; i = i+1;
}
}
else
{
(k=h; k<=mid; k++){
for(k=h;
b[i] = a[k]; i = i+1;
}
}
for(k=low; k<= high; k++)
a[k] = b[k];
}
}

OUTPUT 1:
********** MERGE SORT PROGRAM *********
Enter the number of elements to be sorted
10
Array elements to be sorted are
34 83 89 21 62 36 48 90 36 85
The sorted elements are
21 34 36 36 48 62 83 85 89 90

The time taken to sort is 6051702ns


******** *********************** *******

OUTPUT 2:
********** MERGE SORT PROGRAM *********
Enter the number of elements to be sorted
20
Array elements to be sorted are
56 55 12 91 83 43 62 93 70 33 54 45 57 51 35 17 0 67 23 39
The sorted elements are
0 12 17 23 33 35 39 43 45 51 54 55 56 57 62 67 70 83 91 93

The time taken to sort is 11045347ns


******** *********************** *******
Design and Analysis of Algorithm Lab
/* 6A. Implement in Java, the 0/1 Knapsack problem using Dynamic
Programming method */

import java.util.Scanner;

public class Lab6A {


public static void main(String[] args) {
int v[][]=new int[10][10],
[10][10], w[]=
w[]=new int[10], p[]=new
new int[10];
int
Scanner in = new Scanner(System.
Scanner(System.in);
int i, j;
System.out.println("*************
.println("************* KNAPSACK PROBLEM ***********");
System.out.println("Enter
.println("Enter the total number of items: ");
int n = in.nextInt();
System.out.println("Enter
.println("Enter the weight of each item: ");
(i=1;i<=n;i++)
for(i=1;i<=n;i++)
w[i] = in.nextInt();
System.out.println("Enter
.println("Enter the profit of each item: ");
;i++)
for(i=1;i<=n;i++)
p[i] = in.nextInt();
System.out.println("Enter
.println("Enter the knapsack capacity: ");
int m= in.nextInt();
(m,n,w,p);
displayinfo(m,n,w,p);
(m,n,w,p,v);
knapsack(m,n,w,p,v);
System.out.println("The
.println("The contents of the knapsack table are");
(i=0; i<=n; i++){
for(i=0;
(j=0; j<=m; j++){
for(j=0;
System.out.print(v[i][j]+"
.print(v[i][j]+" " );
}
System.out.println();
.println();
}
(m,n,w,v); //call optimal function
optimal(m,n,w,v);
}

static void displayinfo(


displayinfo(int m,int n,int w[],int p[]){
System.out.println("Entered
.println("Entered information about knapsack problem are");
System.out.println("ITEM
.println("ITEM\tWEIGHT\tPROFIT");
for(int i=1; i<=n; i++)
System.out.println(i+"
.println(i+"\t"+w[i]+"\t"+p[i]);
System.out.println("Capacity
.println("Capacity = "+m);
}

static void knapsack(


knapsack(int m,int n,int w[],int p[],int v[][]){
for(int i=0; i<=n; i++){
for(int j=0; j<=m; j++){
(i==0 ||j==0)
if(i==0
v[i][j]=0;
(j < w[i])
else if(j
v[i][j]=v[i
v[i][j]=v[i-1][j];
else
v[i][j]=
v[i][j]=max(v[i-1][j], v[i-1][j-w[i]]+p[i]);
w[i]]+p[i]);
}
}
}
Design and Analysis of Algorithm Lab
private static int max(int i, int j) {
if(i>j)
return i;
else return j;
}

static void optimal(


optimal(int m,int n,int w[],int v[][]){
int i = n, j = m, item=0;
int x[]=new int[10];
[10];
( i != 0 && j != 0){
while(
(v[i][j] != v[i
if(v[i][j] v[i-1][j]){
x[i] = 1;
j = j
j-w[i];
}
i = i-1;
}
.println("Optimal solution is :"+ v[n][m]);
System.out.println("Optimal
System.out.println("Selected
.println("Selected items are: ");
=1; i<= n;i++)
for(i=1;
if(x[i] == 1){
System.out.print(i+"
.print(i+" ");
item=1;
}
if(item == 0)
System.out.println("NIL
.println("NIL\t
t Sorry ! No item can be placed in Knapsack");
System.out.println("\n*********
n********* *********************** *************");
}
}
Design and Analysis of Algorithm Lab
OUTPUT 1:
**************** KNAPSACK PROBLEM ****************
Enter the total number of items:
4
Enter the weight of each item:
2 3 1 2
Enter the profit of each item:
12 10 15 20
Enter the knapsack capacity:
5
Entered information about knapsack problem are
ITEM WEIGHT PROFIT
1 2 12
2 3 10
3 1 15
4 2 20
Capacity = 5
The contents of the knapsack table are
0 0 0 0 0 0
0 0 12 12 12 12
0 0 12 12 12 22
0 15 15 27 27 27
0 15 20 35 35 47
Optimal solution is :47
Selected items are:
1 3 4
********* ******************************* *************
OUTPUT 2
**************** KNAPSACK PROBLEM ****************
Enter the total number of items:
2
Enter the weight of each item:
4
5
Enter the profit of each item:
34
32
Enter the knapsack capacity:
3
Entered information about knapsack problem are
ITEM WEIGHT PROFIT
1 4 34
2 5 32
Capacity = 3
The contents of the knapsack table are
0 0 0 0
0 0 0 0
0 0 0 0
Optimal solution is :0
Selected items are:
NIL Sorry ! No item can be placed in Knapsack
********* ******************************* *************
Design and Analysis of Algorithm Lab
/*6B. Implement in Java, the 0/1 Knapsack problem using Greedy
method.*/
import java.util.Scanner;
public class Lab6B {
public static void main(String[] args) {
float w[]=new float[10],p[]=new float[10];
float ratio[]=new float[10];
Scanner in = new Scanner(System.in);
int i;
System.out.println("********* KNAPSACK PROBLEM *******");
System.out.println("Enter the total number of items: ");
int n = in.nextInt();
System.out.println("Enter
n("Enter the weight of each item: ");
for(i=1;i<=n;i++)
w[i] = in.nextFloat();
System.out.println("Enter the profit of each item: ");
for(i=1;i<=n;i++)
p[i] = in.nextFloat();
System.out.println("Enter the knapsack capacity: ");
int m= in.nextInt();
for(i=1;i<=n;i++)
ratio[i]=p[i]/w[i];
System.out.println("Information about knapsack problem are");
displayinfo(n,w,p,ratio);
System.out.println("Capacity = "+m);
sortArray(n,ratio,w,p);
System.out.println("
System.out.println("\nDetails after sorting items based on
Profit/Weight ratio in descending order: ");
displayinfo(n,w,p,ratio);
knapsack(m,n,w,p);
System.out.println("*************************************");
}

static void sortArray(int n,float ratio[],float w[],float p[]){


int i,j;
for(i=1; i<=n; i++)
for(j=1; j<=n-i;
i; j++){
if(ratio[j]<ratio[j+1]){
float temp=ratio[j];
ratio[j]=ratio[j+1];
ratio[j+1]=temp;
temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
}
}
Design and Analysis of Algorithm Lab
static void displayinfo(int n,float w[],float p[],float ratio[]){
System.out.println("ITEM
System.out.println("ITEM\tWEIGHT\tPROFIT\tRATIO(PROFIT/WEIGHT)");
tRATIO(PROFIT/WEIGHT)");
for(int i=1; i<=n; i++)
System.out.println(i+"
System.out.println(i+"\t"+w[i]+"\t"+p[i]+"\t"+ratio[i]);
t"+ratio[i]);
}

static void knapsack(int u,int n,float w[],float p[]){


float x[]=new float[10],tp=0;
int i;
for(i=1; i<=n; i++)
x[i]=0;
for(i=1; i<=n; i++){
if(w[i]>u)
break;
else{
x[i]=1;
tp=tp+p[i];
u=(int) (u-
-w[i]);
}
}
if(i<n)
x[i]=u/w[i];
i]=u/w[i];
tp=tp+(x[i]*p[i]);
System.out.println("
System.out.println("\nThe result is = ");
for(i=1; i<=n; i++)
System.out.print("
System.out.print("\t"+x[i]);
System.out.println("
System.out.println("\nMaximum profit is = "+tp);
}
}
Design and Analysis of Algorithm Lab
OUTPUT:

**************** KNAPSACK PROBLEM ****************


Enter
ter the total number of items:
4
Enter the weight of each item:
3 3 5 4
Enter the profit of each item:
6 4 11 16
Enter the knapsack capacity:
6

Information about knapsack problem are


ITEM WEIGHT PROFIT RATIO(PROFIT/WEIGHT)
1 3.0 6.0 2.0
2 3.0 4.0 1.3333334
3 5.0 11.0 2.2
4 4.0 16.0 4.0
Capacity = 6

Details after sorting items based on Profit/Weight ratio in


descending order:
ITEM WEIGHT PROFIT RATIO(PROFIT/WEIGHT)
1 4.0 16.0 4.0
2 5.0 11.0 2.2
3 3.0 6.0 2.0
4 3.0 4.0 1.3333334

The result is =
1.0 0.4 0.0 0.0
Maximum profit is = 20.4
*******************************************************
Design and Analysis of Algorithm Lab
/* 7. From a given vertex in a weighted connected graph, find
shortest paths to other vertices using Dijkstra's algorithm.
algorithm
Write the program in Java.*/

import java.util.Scanner;

public class Lab7 {


public static void main(String[] args) {
int i, j;
int dist[]=new
new int[10],
int visited[]=new int[10];
int cost[][]=new int[10][10], path[]=new int[10];
new int [10];
Scanner in = new Scanner(System.in);
System.out.println("****
.println("**** DIJKSTRA'S ALGORITHM ******");
System.out.println("Enter
.println("Enter the number of nodes: ");
int n = in.nextInt();
System.out.println("Enter
.println("Enter the cost matrix");
++)
for(i=1;i<=n;i++)
(j=1;j<=n;j++)
for(j=1;j<=n;j++)
cost[i][j] = in.nextInt();
System.out.println("The
.println("The entered cost matrix is");
(i=1;i<=n;i++)
for(i=1;i<=n;i++)
{
(j=1;j<=n;j++)
for(j=1;j<=n;j++)
{
System.
System.out.print(cost[i][j]+"\t");
}
System.out.println();
.println();
}
System.out.println("Enter
.println("Enter the source vertex: ");
int sv = in.nextInt();
(cost,dist,sv,n,path,visited);
dij(cost,dist,sv,n,path,visited);
(sv,n,dist,path,visited );
printpath(sv,n,dist,path,visited
System.out.println("
.println("\n*********
n********* *************** *********");
}

static void dij(int


int cost[][],int dist[],int sv,int n,int
int
path[],
path[],int visited[])
{
int count = 2,min,v=0;
for(int i=1; i<=n; i++){
visited[i]=0;
dist[i] = cost[sv][i];
(cost[sv][i] == 999)
if(cost[sv][i]
path[i] = 0;
else
path[i] = sv;
}
visited[sv]=1;
(count<=n){
while(count<=n){
min = 999;
int w=1; w<=n; w++)
for(int
((dist[w]< min) && (visited[w]==0))
if((dist[w]<
Design and Analysis of Algorithm Lab
{
min = dist[w];
v = w;
}
visited[v] = 1;
count++;
int w=1; w<=n; w++){
for(int
((dist[w]) >(dist[v] + cost[v][w]))
if((dist[w])
{
dist[w] = dist[v] + cost[v][w];
path[w] = v;
}

}
}
}

static void printpath(


printpath(int sv,int n,int dist[],int path[],
int visited[]){
for(int w=1; w<=n; w++){
(visited[w] == 1 && w != sv){
if(visited[w]
System.out.println("The
.println("The shortest distance between ");
System.out.println(sv+"
.println(sv+"-> ="+w+" is :"+ dist[w]);
int t=path[w];
System.out.println("The
.println("The path is:");
System.out.print("
.print(" "+w);
while(t != sv){
System.out.print("<
.print("<-->"+t);
t=path[t];
}
System.out.print("<
.print("<-->"+sv);
}
}
}
}
Design and Analysis of Algorithm Lab
OUTPUT :

********* DIJKSTRA'S ALGORITHM *********


Enter the number of nodes:
4
Enter the cost matrix
0 1 4 999 1 0 2 8 4 2 0 3 999 8 3 0
The entered cost matrix is
0 1 4 999
1 0 2 8
4 2 0 3
999 8 3 0
Enter the source vertex:
1
The shortest distance between 1->
1 =2 is :1
The path is:
2<-->1The
>1The shortest distance between 1->
1 =3 is :3
The path is:
3<-->2<-->1The
1The shortest distance between 1->
1 =4 is :6
The path is:
4<-->3<-->2<-->1
********* ************************ *********
Design and Analysis of Algorithm Lab
/* 8. Find Minimum Cost Spanning Tree of a given undirected graph
using Kruskal's algorithm.
algorithm Implement the program in Java
language. */

import java.util.Scanner;

public class Lab8A {

public static void main(String[] args) {


int cost[][]=new
new int
int[10][10];
int i, j,mincost=0;
Scanner in = new Scanner(System.
Scanner(System.in);
System.out.println("*********
.println("********* KRUSKAL'S ALGORITHM *******");
*******")
System.out.println("Enter
.println("Enter the number of nodes: ");
int n = in.nextInt();
System.out.println("Enter
.println("Enter the cost matrix");
(i=1;i<=n;i++){
for(i=1;i<=n;i++){
(j=1;j<=n;j++){
for(j=1;j<=n;j++){
cost[i][j] = in.nextInt();
}
}
.println("The entered cost matrix is");
System.out.println("The
++){
for(i=1;i<=n;i++){
(j=1;j<=n;j++){
for(j=1;j<=n;j++){
System.out.print(cost[i][j]+"
.print(cost[i][j]+"\t");
}
System.out.println();
.println();
}
mincost=kruskals(n,mincost,cost);
(n,mincost,cost);
System.out.println("The
.println("The minimum spanning tree cost is: “);
System.out.println(mincost);
.println(mincost);
System.out.println("*********
.println("********* ****************** **********");
}

static int kruskals(


kruskals(int n,int mincost,int cost[][] ) {
int ne = 1,a=0,u=0,b=0,v=0,min;
int parent[]=new
new int
int[10];
while(ne < n){
min=999;
for(int i=1; i<=n; i++){
int j=1; j<=n; j++){
for(int
if(cost[i][j] < min){
min = cost[i][j];
a=u=i;
b=v=j;
}
}
}
(parent[u]>0)
while(parent[u]>0)
u = parent[u];
(parent[v]>0)
while(parent[v]>0)
v = parent[v];
Design and Analysis of Algorithm Lab
if(u != v)
{
System.out.println((ne++)+">minimum
.println((ne++)+">minimum edge is :”);
System.out.println(“("+a+","+b+")
.println(“("+a+","+b+") and its cost is:"+min);
mincost += min;
parent[v] = u;
}
cost[a][b] = cost[b][a] = 999;
}
return mincost;
}

OUTPUT
********* KRUSKAL'S ALGORITHM *********
Enter the number of nodes:
5
Enter the cost matrix
0 1 2 999 6 1 0 3 999
999 2 3 0 4 999 999 999
4 0 5 6 999 999 5 0
The entered cost matrix is
0 1 2 999 6
1 0 3 999 999
2 3 0 4 999
999 999 4 0 5
6 999 999 5 0
1> minimum edge is :(1,2) and its cost is:1
2> minimum edge is :(1,3) and its cost is:2
3> minimum edge is :(3,4) and its cost is:4
4> minimum edge is :(4,5) and its cost is:5
The minimum spanning tree cost is : 12
********* *********************** **********
Design and Analysis of Algorithm Lab

/* 8B. Find Minimum Cost Spanning Tree of a given undirected


graph using Prim's algorithm.
algorithm. Implement the program in Java
language. */

import.java.util.scanner;

public class Lab8B {


public static void main(String[] args) {
int cost[][]=new
new int
int[10][10];
int i, j, mincost = 0;
Scanner in = new Scanner(System.in);
System.out.println("*********
.println("********* PRIMS ALGORITHM *********");
System.out.println("Enter
.println("Enter the number of nodes");
int n = in.nextInt();
System.out.println("Enter
.println("Enter the cost matrix");
(i=1; i<=n; i++){
for(i=1;
(j=1; j<=n; j++){
for(j=1;
cost[i][j] = in.nextInt();
}
}
System.out.println("The
.println("The entered cost matrix is");
(i=1; i<=n; i++){
for(i=1; i+
(j=1; j<=n; j++){
for(j=1;
System.
System.out.print(cost[i][j]+"\t");
}
System.out.println();
.println();
}
System.out.println("Minimum
.println("Minimum Spanning Tree Edges and costs are");
mincost=prims(cost,n,mincost);
(cost,n,mincost);
System.out.println("The
.println("The minimum spanning tree cost is”);
System.out.println
.println (+mincost);
System.out.println("*******
.println("******* ********************* *******");

static int prims(int


int cost[][],int n,int mincost){
int nearV[]=new
new int[10],t[][]=new
int [10][3],u = 0,i,j,k;
int[10][3],u
(i=2; i<=n; i++)
for(i=2;
nearV[i]=1;
nearV[1]=0;
(i=1; i<n; i++)
for(i=1;
{
int min=999;
(j=1;j<=n;j++)
for(j=1;j<=n;j++)
{
(nearV[j]!=0 && cost[j][nearV[j]]<min)
if(nearV[j]!=0
{
min=cost[j][nearV[j]];
u=j;
}
}
Design and Analysis of Algorithm Lab
t[i][1] = u;
t[i][2] = nearV[u];
mincost += min;
nearV[u] = 0;
(k=1; k<=n; k++){
for(k=1;
(nearV[k] != 0 && cost[k][nearV[k]] > cost[k][u])
if(nearV[k]
nearV[k] = u;
}
System.out.println(i+")
.println(i+") Minimum edge is ("+t[i][1]);
System.out.println(","+t[i][2]+")
.println(","+t[i][2]+") and its cost is :"+min);
}
return mincost;
}

}
OUTPUT 1:
************** PRIMS ALGORITHM **************
Enter the number of nodes
5
Enter the cost matrix
0 1 2 999 6 1 0 3 999 999 2
3 0 4 999 999 999 4 0 5 6 999
999 5 0
The entered cost matrix is
0 1 2 999 6
1 0 3 999 999
2 3 0 4 999
999 999 4 0 5
6 999 999 5 0
Minimum Spanning Tree Edges and costs are
1) Minimum edge is (2,1) and its cost is :1
2) Minimum edge is (3,1) and its cost is :2
3) Minimum edge is (4,3) and its cost is :4
4) Minimum edge is (5,4) and its cost is :5
The minimum spanning tree cost is 12
******* ******************************** *******
Design and Analysis of Algorithm Lab
/* 9A. Write Java programs to implement All
All-Pairs
Pairs Shortest Paths
problem using Floyd's algorithm.*/

import java.util.Scanner;

public class Lab9A {


public static void main(String[] args) {
int a[][]=new int[10][10];
int i, j;
Scanner in = new Scanner(S
Scanner(System.in);
System.out.println("***********FLOYD'SALGORITHM**********");
.println("***********FLOYD'SALGORITHM**********");
System.out.println("Enter
.println("Enter the number of vertices: ")
int n = in.nextInt();
System.out.println("Enter
.println("Enter the adjacency matrix");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
a[i][j] = in.nextInt
in.nextInt();
System.out.println("Entered
.println("Entered adjacency matrix is: ");
for(i=1;i<=n;i++) {
for(j=1; j<=n; j++) {
System.out.print(a[i][j]+"
.print(a[i][j]+"\t");
}
System.out.println();
.println();
}
floyd(a,n);
System.out.println("All
.println("All pair shortest path matrix:");
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++)
System.out.print(a[i][j]+"
.print(a[i][j]+"\t");
System.out.println();
.println();
}
System.out.println("************
.println("************ ********* **************");
}

static void floyd(int a[][],int n) {


for (int k=1; k<=n; k++) {
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
a[i][j] = min
min(a[i][j], a[i][k] + a[k][j]);
}
}

static int min(int a,int b) {


if(a>b)
return b;
else
return a;
}

}
Design and Analysis of Algorithm Lab
OUTPUT :

***********FLOYD'S ALGORITHM**********

Enter the number of vertices:


4
Enter the adjacency matrix
0 1 8 5 1 0 2 999 8 2
0 3 5 999 3 0
Entered adjacency matrix is:
0 1 8 5
1 0 2 999
8 2 0 3
5 999 3 0
All pair shortest path matrix:
0 1 3 5
1 0 2 5
3 2 0 3
5 5 3 0

************** ********* **************


Design and Analysis of Algorithm Lab
/* 9B. Write Java programs to implement Travelling Sales Person
problem using Dynamic programming. */

import java.util.Scanner;

public class Lab9B {


public static void main(String[] args) {
int c[][]=new int[10][10],
[10][10], tour[]=
tour[]=new int[10];
scanner in = new Scanner(System.
Scanner(System.in);
int i, j,cost;
System.out.println("****
.println("**** TSP DYNAMIC PROGRAMMING *******");
System.out.println("Enter
.println("Enter the number of cities: ");
int n = in.nextInt();
if(n==1) {
System.out.println("Path
.println("Path is not possible");
System.exit(0);
}
System.out.println("Enter
.println("Enter the cost matrix");
(i=1;i<=n;i++)
for(i=1;i<=n;i++)
(j=1;j<=n;j++)
for(j=1;j<=n;j++)
c[i][j] = in.nextInt();
System.out.println("The
.println("The entered cost matrix is");
for(i=1;i<=n;i++) {
j=1;j<=n;j++) {
for(j=1;j<=n;j++)
System.out.print(c[i][j]+"
.print(c[i][j]+"\t");
}
System.out.println();
.println();
}
(i=1;i<=n;i++)
for(i=1;i<=n;i++)
tour[i]=i;
cost = tspdp(c,(c, tour, 1, n);
System.out.println("The
.println("The accurate path is");
for(i=1;i<=n;i++)
System.out.print(tour[i]+"
.print(tour[i]+"->");
.println("1");
System.out.println("1");
System.out.println("The
.println("The accurate mincost is "+cost);
.println("******* ************* ***************");
System.out.println("*******

static int tspdp(int


int c[][], int tour[], int start, int n) {
int mintour[]=new
new int[10],
int temp[]=new int[10],
[10], mincost=999,
ccost, i, j, k;
if(start == n-1) {
return (c[tour[n-1]][tour[n]]
(c[tour[n + c[tour[n]][1]);
}
for(i=start+1; i<=n; i++) {
(j=1; j<=n; j++)
for(j=1;
temp[j] = tour[j];
temp[start+1] = tour[i];
temp[i] = tour[start+1];
Design and Analysis of Algorithm Lab
((c[tour[start]][tour[i]]+(ccost=tspdp(c,temp,start+1,n)))<mincost){
if((c[tour[start]][tour[i]]+(ccost= (c,temp,start+1,n)))<mincost){
mincost = c[tour[start]][tour[i]] + ccost;
(k=1; k<=n; k++)
for(k=1;
mintour[k] = temp[k];
}
}
(i=1; i<=n; i++)
for(i=1;
tour[i] = mintour[i];
return mincost;
}
}

OUTPUT :

******* TSP DYNAMIC PROGRAMMING *******

Enter the number of cities:


4
Enter the cost matrix
0 1 3 6 1 0 2 3 3 2 0
1 6 3 1 0
The entered cost matrix is
0 1 3 6
1 0 2 3
3 2 0 1
6 3 1 0
The accurate path is
1->2->4->3->1
The accurate mincost is 8

******* *********************** ***************


Design and Analysis of Algorithm Lab
/* 10A 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 Lab10A {


static int c=0;
public static void main(String[] args) {
int w[]=new int[10];
[10];
int n, d, i, sum=0;
int x[]=new int[10];
[10];
Scanner in=new Scanner(System.in
Scanner(System.
System.out.println("**********
.println("********** SUBSET PROBLEM ************");
System.out.println("Enter
.println("Enter the number of elements: ");
n=in.nextInt();
System.out.println("Enter
.println("Enter the elements in increasing order");
for(i=0;i<n;i++)
w[i]=in.nextInt();
System.out.println("Enter
.println("Enter the value of d: ");
d=in.nextInt();
for(i=0;i<n;i++)
sum=sum+w[i];
System.out.println("SUM
.println("SUM ="+sum);
(sum < d || w[0] > d){
if(sum
System.out.println("Subset
.println("Subset is not possible ! ");
System.out.println("**********
.println("********** *********** *************");
System.exit(0);
(0);
}
(0,0,sum,x,w,d);
subset(0,0,sum,x,w,d);
if(c==0)
System.out.println("Subset
.println("Subset is not possible ! ");
System.out.println("
.println("\n**********
n********** ********* *************");
}

static void subset(int


int cs, int k, int r,int x[],int w[],int
w[], d){
x[k] = 1;
if(cs+w[k] == d) {
c++;
System.out.print("
.print("\nSolution "+c+" is {");
for(int i=0;i<=k;i++)
if(x[i] == 1) {
System.out.print(w[i]+"
.print(w[i]+" ");
}
System.out.print("}");
.print("}");
}
((cs + w[k] + w[k+1]) <= d)
else if((cs
(cs + w[k], k+1, r
subset(cs r-w[k],x,w,d);
if((cs + r - w[k]) >= d && (cs + w[k+1]) <= d) {
Design and Analysis of Algorithm Lab
x[k] = 0;
(cs, k+1, r-w[k],x,w,d);
subset(cs, r
}

}
}
OUTPUT 1:
*********** SUBSET PROBLEM ************
Enter the number of elements:
5
Enter the elements in increasing order:
1 2 3 6 8
Enter the value of d:
9
SUM =20

Solution 1 is {1 2 6 }
Solution 2 is {1 8 }
Solution 3 is {3 6 }
********** ****************** *************
OUTPUT 2:
*********** SUBSET PROBLEM ************
Enter the number of elements:
3
Enter the elements in increasing order:
5 8 10
Enter the value of d:
25
SUM =23
Subset is not possible !
********** ****************** *************

OUTPUT 3:
*********** SUBSET PROBLEM ************
Enter the number of elements:
3
Enter the elements in increasing order:
3 5 9
Enter the value of d:
7
SUM =17
Subset is not possible !

********** ****************** *************


Design and Analysis of Algorithm Lab
/*10B Design and implement the presence of Hamiltonian Cycle in
an undirected Graph G of n vertices.*/
import java.util.Scanner;
public class Lab10B {
static int n;
public static void main(String[] args) {
Scanner in = new Scanner(System.
Scanner(System.in);
System.out.println("Enter
.println("Enter no. of vertices");
n=in.nextInt();
int graph[][]=new
new int[10][10];
int
System.out.println("Enter
.println("Enter adjacency matrix of graph");
for(int i=1;i<n;i++)
;i++)
for(int j=0;j<nn;j++)
graph[i][j] =in.nextInt();
System.out.println("Entered
.println("Entered adjacency matrix of graph is");
for(int i=0;i<n;i++)
;i++) {
for(int j=0;j<n;j++)
;j++) {
System.out.print("
.print("\t"+graph[i][j]);
}
System.out.println();
.println();
}
(graph);
hamCycle(graph);
System.out.println("
.println("\n*********************************
**********************\n");
}

static void printSolution(


printSolution(int path[]){
System.out.println("Solution
.println("Solution Exists:");
System.out.println("
.println(" Following is one Hamiltonian Cycle ");
for (int i = 0; i <<n; i++)
System.out.println(path[i]);
.println(path[i]);
System.out.println(path[0]);
.println(path[0]);
}

static boolean isSafe(int


isSafe( v,int graph[][],int path[],int
int pos){
if (graph[path[pos-1]][v]
(graph[path[pos == 0)
return false
false;
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false
false;
return true;
}

/* A recursive utility function to solve Hamiltonian cycle


problem */
static boolean hamCycleUtil(int
hamCycleUtil( graph[][],int path[],int
int pos){
if (pos == n){
if (graph[path[pos-1]][path[0]]
(graph[path[pos == 1)
return true
true;
else return false;
false
}
Design and Analysis of Algorithm Lab
for (int v = 1; v < n; v++){
if (isSafe(v,
(v, graph, path, pos)){
path[pos] = v;
if (hamCycleUtil
hamCycleUtil (graph, path, pos+1) == true)
return true;
path[pos] = -1;
}
}
return false;
}

/* This function solves the Hamiltonian Cycle problem using


Backtracking. It mainly uses hamCycleUtil()
hamCycleUtil() to solve the problem.
It returns false if there is no Hamiltonian Cycle possible,
otherwise return true and prints the path.This function prints
one of the feasible solutions. */
static boolean hamCycle(int
hamCycle( graph[][]){
int path[] = new int
int[n+1];
for (int i = 0; i < n; i++)
path[i] = -1;
-
path[0] = 0;
if (hamCycleUtil
hamCycleUtil(graph, path, 1) == false){
System.out.println("
.println("\nSolution
nSolution does not exist");
return false
false;
}
(path);
printSolution(path);
return true;
}
}
OUTPUT 1:
*******************Hamiltonian cycle*****************
Enter no. of vertices
5
Enter adjacency matrix of graph
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

Entered adjacency matrix of graph is


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
Solution Exists:
Following is one Hamiltonian Cycle
0 -->1 -->2 -->4 -->3
>3 -->0
******************************************************

OUTPUT 2:
*******************Hamiltonian cycle*****************
Enter no. of vertices
Department of CSE, DBIT,Bengaluru
Design and Analysis of Algorithm Lab
5
Enter adjacency matrix of graph
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
Entered adjacency matrix of graph is
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

Solution does not exist


******************************************************

Department of CSE, DBIT,Bengaluru

You might also like