You are on page 1of 96

AMC ENGINEERING COLLEGE,

BANGALORE

Department of Computer Science & Engineering

B.E IV Semester

DESIGN AND ANALYSIS OF ALGORITHM LABORATORY


(15CSL47)
CBCS SCHEME

Name: …………………..

USN: …………………...

VISVESVARAYA TECHNOLOGICAL UNIVERSITY


“Jnana Sangama”, BELAGAVI – 590 018
KARNATAKA
Design and Analysis of Algorithm Laboratory

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.

EXP CONTENTS
NO.
A. Create a Java class called Student with the following details as variables within it.
(i) USN
(ii) Name
1 (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.
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 “/”.

Dept. of CSE,AMCEC 15CSL47 Page 2


Design and Analysis of Algorithm Laboratory

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

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.
4 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.
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
5 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 (a) Dynamic Programming method
6 (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.
Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's
8 algorithm. Use Union-Find algorithms in your program.
Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's
9 algorithm.
Write Java programs to
10 (a) Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
(b) Implement Travelling Sales Person problem using Dynamic programming.
11 (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.
12 Design and implement the presence of Hamiltonian Cycle in an undirected Graph G of n
vertices.

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

Dept. of CSE,AMCEC 15CSL47 Page 3


Design and Analysis of Algorithm Laboratory

Course Outcomes: The students should 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.

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 (Twelve problems) are to be included for practical examination.
Students are allowed to pick one experiment from the lot.

To generate the data set use random number generator function. Strictly follow the instructions as
printed on the cover page of answer script for breakup of marks

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


Change of experiment is allowed only once and marks allotted to the procedure

Dept. of CSE,AMCEC 15CSL47 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 n Student objects and print the USN, Name, Branch, and
Phone of these objects with suitable headings.

import java.lang.*;
import java.util.*;

class STUDENT
{
String usn;
String name;
String branch;
long phno;
public void getdata()
{
Scanner read=new Scanner(System.in);
System.out. println("Enter USN,Name,Branch,PhNo");
usn=read.next();
name=read.next();
branch=read.next();
phno=read.nextLong();
}
public void display()
{
System.out. println("***************");
System.out .println("Student USN="+usn);
System.out .println("Student Name="+name);
System.out. println("Student Branch="+branch);
System.out .println("Student PhNo="+phno);
}
}

Dept. of CSE,AMCEC 15CSL47 Page 5


Design and Analysis of Algorithm Laboratory

class PROGRAMA1
{
public static void main(String args[])
{
int n;
Scanner read=new Scanner(System.in);
System.out. println("Enter no of students");
n=read.nextInt();
STUDENT s[]= new STUDENT[n];
System.out.println("Enter the student deails");
for(int i=0;i<n;i++)
{
s[i]=new STUDENT();
s[i].getdata();
}
System.out.println(".....Student Details.....");
for(int i=0;i<n;i++)
{
s[i].display();
System.out.println();
}
}
}

OUTPUT:-
Enter no of students
2
Enter the student deails
Enter USN,Name,Branch,PhNo
129 aaa cs 9999
Enter USN,Name,Branch,PhNo
130 bbb cs 4444
.....Student Details.....
***************
student USN=129
student Name=aaa
student Branch=cs
student PhNo=9999

Dept. of CSE,AMCEC 15CSL47 Page 6


Design and Analysis of Algorithm Laboratory

***************
student USN=130
student Name=bbb
student Branch=cs
student PhNo=4444
*****

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

import java.lang.*;
import java.util.*;
class STACK
{
int st[]=new int[10];
int top;
int size;
STACK()
{
top=-1;
size=5;
}
void push(int item)
{
if(top==size-1)
System.out.println("Stack overflow...");

else
{
st[++top]=item;
}
}
void pop()
{
if(top==-1)
System.out.println("Stack underflow...");
else
{
System.out.println("Item popped=" +st[top--]);
}
}
void display()
{
if(top==-1)
Dept. of CSE,AMCEC 15CSL47 Page 7
Design and Analysis of Algorithm Laboratory

{
System.out.println("Stack Underflow");
}
else
{
for(int i=0;i<=top;i++)
{
System.out.println(+st[i]);
}
}
}
}
public class Program2
{
public static void main(String args[])
{
STACK Ob=new STACK();
Scanner read=new Scanner(System.in);
for(;;)
{
System.out.println("Enter 1:Push 2:Pop 3:Display 4:Exit");
int ch=read.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter item");
int item=read.nextInt();
Ob.push(item);
break;
case 2:
Ob.pop();
break;
case 3:
System.out.println("Stack contains...");
Ob.display();
break;
default:
return;1
}
}
}
}

Dept. of CSE,AMCEC 15CSL47 Page 8


Design and Analysis of Algorithm Laboratory

OUTPUT:-
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
5
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
10
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
15
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
20
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
25
Enter 1:Push 2:Pop 3:Display 4:Exit
1
Enter item
30
Stack overflow...
Enter 1:Push 2:Pop 3:Display 4:Exit

Dept. of CSE,AMCEC 15CSL47 Page 9


Design and Analysis of Algorithm Laboratory

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.

import java.util.Scanner;

class Staff
{
String StaffID,Name,Phone,Salary;
Scanner input = new Scanner(System.in);
void read()
{
System.out.println("Enter StaffID");
StaffID = input.nextLine();
System.out.println("Enter Name");
Name = input.nextLine();
System.out.println("Enter Phone");
Phone = input.nextLine();
System.out.println("Enter Salary");
Salary = input.nextLine();
}
void display()
{
System.out.printf("\n%-15s","STAFFID:");
System.out.printf("%-15s \n",StaffID);
System.out.printf("%-15s","NAME:");
System.out.printf("%-15s \n",Name);
System.out.printf("%-15s","PHONE:");
System.out.printf("%-15s \n",Phone);
System.out.printf("%-15s","SALARY:");
System.out.printf("%-15s \n",Salary);
}
}
class Teaching extends Staff
{
String Domain,Publication;
void read_Teaching()
{
super.read();
System.out.println("Enter Domain");
Domain = input.nextLine();
System.out.println("Enter Publication");
Publication = input.nextLine();

Dept. of CSE,AMCEC 15CSL47 Page 10


Design and Analysis of Algorithm Laboratory

}
void display()
{
super.display();
System.out.printf("%-15s","DOMAIN:");
System.out.printf("%-15s \n",Domain);
System.out.printf("%-15s","PUBLICATION:");
System.out.printf("%-15s \n",Publication);
}
}
class Technical extends Staff
{
String Skills;
void read_Technical()
{
super.read();
System.out.println("Enter Skills");
Skills = input.nextLine();
}
void display()
{
super.display();
System.out.printf("%-15s","SKILLS:");
System.out.printf("%-15s \n",Skills);
}
}
class Contract extends Staff
{
String Period;
void read_Contract()
{
super.read();
System.out.println("Enter Period");
Period = input.nextLine();
}
void display()
{
super.display();
System.out.printf("%-15s","PERIOD:");
System.out.printf("%-15s \n",Period);
}
}
class Program2
{
public static void main(String[] args)

Dept. of CSE,AMCEC 15CSL47 Page 11


Design and Analysis of Algorithm Laboratory

{
Scanner input = new Scanner(System.in);
System.out.println("Enter number of staff details to be created");
int n = input.nextInt();
Teaching steach[] = new Teaching[n];
Technical stech[] = new Technical[n];
Contract scon[] = new Contract[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter Teaching staff information");
steach[i] = new Teaching();
steach[i].read_Teaching();
}
for(int i=0;i<n;i++)
{
System.out.println("Enter Technical staff information");
stech[i] = new Technical();
stech[i].read_Technical();
}
for(int i=0;i<n;i++)
{
System.out.println("Enter Contract staff information");
scon[i] = new Contract();
scon[i].read_Contract();
}
System.out.println("\n STAFF DETAILS: \n");
System.out.println("-----TEACHING STAFF DETAILS-----");
for(int i=0;i<n;i++)
{
steach[i].display();
}
System.out.println();

System.out.println("-----TECHNICAL STAFF DETAILS-----");


for(int i=0;i<n;i++)
{
stech[i].display();
}
System.out.println();

System.out.println("-----CONTRACT STAFF DETAILS-----");


for(int i=0;i<n;i++)
{
scon[i].display();
}

Dept. of CSE,AMCEC 15CSL47 Page 12


Design and Analysis of Algorithm Laboratory

input.close();
}
}

OUTPUT:
Enter number of staff details to be created
2
Enter Teaching staff information
Enter StaffID
1AM001
Enter Name
PALLAVI
Enter Phone
1111
Enter Salary
15000
Enter Domain
CSE
Enter Publication
5
Enter Teaching staff information
Enter StaffID
1AM002
Enter Name
KRITHIKA
Enter Phone
2222
Enter Salary
20000
Enter Domain
CSE
Enter Publication
3
Enter Technical staff information
Enter StaffID
1AM003
Enter Name
RITA
Enter Phone
3333
Enter Salary
15000
Enter Skills

Dept. of CSE,AMCEC 15CSL47 Page 13


Design and Analysis of Algorithm Laboratory

JAVA
Enter Technical staff information
Enter StaffID
1AM004
Enter Name
RIYA
Enter Phone
4444
Enter Salary
15000
Enter Skills
PYTHON
Enter Contract staff information
Enter StaffID
1AM005
Enter Name
DEVI
Enter Phone
5555
Enter Salary
20000
Enter Period
5
Enter Contract staff information
Enter StaffID
1AM006
Enter Name
RAHUL
Enter Phone
6666
Enter Salary
15000
Enter Period
3

STAFF DETAILS:

-----TEACHING STAFF DETAILS-----

STAFFID: 1AM001
NAME: PALLAVI
PHONE: 1111
SALARY: 15000
DOMAIN: CSE
PUBLICATION: 5

Dept. of CSE,AMCEC 15CSL47 Page 14


Design and Analysis of Algorithm Laboratory

STAFFID: 1AM002
NAME: KRITHIKA
PHONE: 2222
SALARY: 20000
DOMAIN: CSE
PUBLICATION: 3

-----TECHNICAL STAFF DETAILS-----

STAFFID: 1AM003
NAME: RITA
PHONE: 3333
SALARY: 15000
SKILLS: JAVA

STAFFID: 1AM004
NAME: RIYA
PHONE: 4444
SALARY: 15000
SKILLS: PYTHON

-----CONTRACT STAFF DETAILS-----

STAFFID: 1AM005
NAME: DEVI
PHONE: 5555
SALARY: 20000
PERIOD: 5

STAFFID: 1AM006
NAME: RAHUL
PHONE: 6666
SALARY: 15000
PERIOD: 3
BUILD SUCCESSFUL (total time: 1 minute 49 seconds)

Dept. of CSE,AMCEC 15CSL47 Page 15


Design and Analysis of Algorithm Laboratory

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;
class Customer
{
String name,date_of_birth;
void readdata()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Customer name");
name=sc.next();
System.out.println("Enter date of birth in dd/mm/yyyy format");
date_of_birth=sc.next();
sc.close();
}
void display()
{
StringTokenizer st = new StringTokenizer(date_of_birth,"/");
System.out.println("The details of customer are");
System.out.print("<Name,DD,MM,YYYY>"+name);
while(st.hasMoreTokens())
System.out.print(","+st.nextToken());
}
}
public class Prgm2b
{
public static void main(String[] args)
{
Customer c = new Customer();
c.readdata();
c.display();
}
}

OUTPUT:-
Enter the Customer name
Ramya
Enter date of birth in dd/mm/yyyy format
10/12/1985
The details of customer are
<Name,DD,MM,YYYY>Ramya,10,12,1985BUILD SUCCESSFUL (total time: 22 seconds)

Dept. of CSE,AMCEC 15CSL47 Page 16


Design and Analysis of Algorithm Laboratory

ALTERNATE PROGRAM

package customer;
import java.lang.*;
import java.util.*;

public class CUSTOMER


{
String name;
String DOB;
void getdata()
{
Scanner read=new Scanner (System.in);
System.out.println("Enter name&dob in dd/mm/yyyy format");
name=read.next();
DOB=read.next();
}
void display()
{
System.out.println("Customer name="+name);
StringTokenizer remove=new StringTokenizer(DOB,"/");
System.out.println("customer date of birth=");
while(remove.hasMoreTokens())
{
System.out.println(" "+remove.nextToken());
}
}
public static void main(String args[])
{
CUSTOMER ob=new CUSTOMER();
ob.getdata();
ob.display();

}
}
output:
Enter name&dob
zlatan
05/02/2000
Customer name=zlatan
customer date of birth=
05
02
2000

Dept. of CSE,AMCEC 15CSL47 Page 17


Design and Analysis of Algorithm Laboratory

3a. Write a Java program to read two integers a and b. Compute a/b and print, when b is not
zero. Raise an exception when b is equal to zero.

import java.lang.*;
import java.util.*;
public class DIVIDE1
{
public static void main(String[] args)
{
int a,b,result;
Scanner read=new Scanner (System.in);
System.out.println("enter a&b");
a=read.nextInt();
b=read.nextInt();
try
{
result=a/b;
System.out.println("result="+result);
}
catch(Exception e)
{
System.out.println("Exception error="+e);
}
}
}

output:
enter a&b
40
2
result=20

output:-
enter a&b
50 0
Exception error=java.lang.ArithmeticException: / by zero

ALTERNATE PROAGRAM
import java.util.*;
class ExceptionDemo
{
public static void main(String[] args)
{
int a,b,result;
Scanner s= new Scanner(System.in);

Dept. of CSE,AMCEC 15CSL47 Page 18


Design and Analysis of Algorithm Laboratory

System.out.println("Enter the integer a and b");


a=s.nextInt();
b=s.nextInt();
try
{
result=a/b;
System.out.println("The result after division is" +result);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Run:
Enter the integer a and b
10
5
The result after division is2
BUILD SUCCESSFUL (total time: 7 seconds)

Run:
Enter the integer a and b
5
0
java.lang.ArithmeticException: / by zero
at ExceptionDemo.main(Prgm3a.java:14)
BUILD SUCCESSFUL (total time: 4 seconds)

Dept. of CSE,AMCEC 15CSL47 Page 19


Design and Analysis of Algorithm Laboratory

3b. 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.*;
import java.io.*;
class rand extends Thread
{
public int result;
static int num;
public int generate()

Random rangen=new Random();


num=rangen.nextInt(100);
return(num);
}
public void run()
{
while(true)
{
try
{
result=generate();
System.out.println("Random number:"+result);
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
System.out.println("Exception in Rand"+ex);
}
}
}
}
class square extends Thread
{
public int sqnum(int a)
{
return(a*a);
}
public void display(int a)
{
System.out.println("Square:"+a);
}
public void run()

Dept. of CSE,AMCEC 15CSL47 Page 20


Design and Analysis of Algorithm Laboratory

{
while(true)
{
try
{
display(sqnum(rand.num));
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
System.out.println("Exception in Rand"+ex);
}
}
}
}
class cube extends Thread
{
public int cubenum(int a)
{
return(a*a*a);
}
public void display(int a)
{
System.out.println("Cube:"+a);
}
public void run()
{
while(true)
{
try
{
display(cubenum(rand.num));
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
System.out.println("Exception in Rand"+ex);
}
}
}
}
public class Prgm3b
{
public static void main(String[] args) throws Exception
{

Dept. of CSE,AMCEC 15CSL47 Page 21


Design and Analysis of Algorithm Laboratory

rand obj_rand=new rand();


obj_rand.start();
square obj_sq=new square();
obj_sq.start();
cube obj_cu=new cube();
obj_cu.start();
}
}

OUTPUT:-
Cube:91125
Square:3249
Random number:57
Square:3249
Random number:16
Cube:185193
Cube:4096
Random number:16
Square:256
Square:256
Cube:3375
Random number:15
Cube:3375
Random number:13
Square:225
Cube:2197
Square:169
Random number:56
Cube:175616
Random number:38
Square:0
Cube:54872
Square:1444
Random number:18
Cube:54872
Random number:45
Square:2025

ALTERNATE PROGRAM

Dept. of CSE,AMCEC 15CSL47 Page 22


Design and Analysis of Algorithm Laboratory

import java.util.Random;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

class CSE1 extends Thread


{
int n;

void generate() throws InterruptedException


{
Scanner read = new Scanner(System.in);
Random rand =new Random();
System.out.println("enter n");
n= read.nextInt();
System.out.println("random number generated");
for(int i=0;i<n;i++)
{
System.out.println(rand.nextInt(1000));
sleep(1000);

class CSE2 extends Thread


{
int n;

void square()
{
Scanner read = new Scanner(System.in);
System.out.println("enter n");
n= read.nextInt();
System.out.println("squaring number="+(n*n));
}
}

class CSE3 extends Thread


{
int n;
void cube()

Dept. of CSE,AMCEC 15CSL47 Page 23


Design and Analysis of Algorithm Laboratory

{
Scanner read = new Scanner(System.in);
System.out.println("enter n");
n= read.nextInt();
System.out.println("cubing number="+(n*n*n));
}
}
public class AMC
{

public static void main(String[] args) throws InterruptedException


{
ISE1 ob1= new CSE1();
ISE2 ob2= new CSE2();
ISE3 ob3= new CSE3();
ob1.generate();
ob2.square();
ob3.cube();
}

Dept. of CSE,AMCEC 15CSL47 Page 24


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.*;
import java.util.Scanner;
public class program4
{
public static int partition(int a[],int low,int high)
{
int i=low+1, j=high, pivot=a[low];
while(i<=j)
{
while(a[i]<=pivot)
{
i++;
}
while(a[j]>pivot)
{
j--;
}
if(i<j)
{
Swap(a,i,j);
}
}

Swap(a,low,j);
return j;
}

public static void Swap(int a[],int x,int y)


{
int temp=a[x];
a[x]=a[y];
a[y]=temp;
}
public static void divide(int a[],int low,int high)
{
if(low<high)
{
int j=partition(a,low,high);

Dept. of CSE,AMCEC 15CSL47 Page 25


Design and Analysis of Algorithm Laboratory

divide(a,low,j-1);
divide(a,j+1,high);
}
}
public static void main(String[] args)
{
int n,i;
int a[]=new int[500];
Scanner read = new Scanner(System.in);
Random rand = new Random();
System.out.println("Enter n");
n=read.nextInt();
System.out.println("Enter item");
for(i=0;i<n;i++)
{
a[i]=rand.nextInt(1000);
System.out.print(" " +a[i]);
}
System.out.println();
long t1=System.nanoTime();
divide(a,0,n-1);
long t2=System.nanoTime();
System.out.println("\nTime Taken=" +(t2-t1));
System.out.println("***Sorted Array***");
for(i=0;i<n;i++)
{
System.out.print(" " +a[i]);
}
}
}

OUTPUT:-

Enter n
5
Enter item
256 180 775 926 748
Time Taken=6935
***Sorted Array***
180 256 748 775 926BUILD SUCCESSFUL (total time: 2 seconds)
Enter n
10
Enter item
483 903 346 706 722 412 871 709 454 428
Time Taken=9432

Dept. of CSE,AMCEC 15CSL47 Page 26


Design and Analysis of Algorithm Laboratory

***Sorted Array***
346 412 428 454 483 706 709 722 871 903BUILD SUCCESSFUL (total time: 3 seconds)
run:
Enter n
15
Enter item
257 765 751 826 857 274 34 143 521 667 790 302 857 507 895
Time Taken=10264
***Sorted Array***
34 143 257 274 302 507 521 667 751 765 790 826 857 857 895BUILD SUCCESSFUL (total
time: 3 seconds)
run:
Enter n
20
Enter item
244 255 917 852 370 332 673 316 980 769 596 372 346 711 785 70 950 930 748 498
Time Taken=11651
***Sorted Array***
70 244 255 316 332 346 370 372 498 596 673 711 748 769 785 852 917 930 950 980BUILD
SUCCESSFUL (total time: 4 seconds)
run:
Enter n
25
Enter item
662 229 440 260 743 183 740 315 32 493 524 528 174 954 446 40 870 161 43 140 504 834 734
113 285

Time Taken=12483
***Sorted Array***
32 40 43 113 140 161 174 183 229 260 285 315 440 446 493 504 524 528 662 734 740 743 834
870 954BUILD SUCCESSFUL (total time: 2 seconds)

ALTERNATE PROGRAM
import java.lang.*;
import java.util.*;
public class QSORT
{
public static int partition(int a[], int low, int high)
{
int pivot=a[low], i=low+1,j=high;
while(i<=j)
{
while(a[i]<=pivot)
{
i++;

Dept. of CSE,AMCEC 15CSL47 Page 27


Design and Analysis of Algorithm Laboratory

}
while(a[j]>pivot)
{
j--;
}
if(i<j)
{
swap(a,i,j);
}
}
swap(a,low,j);
return j;

}
public static void swap(int a[],int x, int y)
{
int temp=a[x];
a[x]=a[y];
a[y]=temp;
}
public static void divide(int a[],int low, int high)
{
if(low<high)
{
int j=partition(a,low,high);
divide(a,low,j-1);
divide(a,j+1,high);
}
}

public static void main(String[] args)throws ArrayIndexOutOfBoundsException


{
int n,i;
int a[]=new int[5000];
Scanner read=new Scanner(System.in);
Random rand=new Random();
System.out.println("enter n");
n=read.nextInt();
for(i=0;i<n;i++)
{
a[i]=rand.nextInt(1000);
System.out.print(" "+a[i]);
}
System.out.println();

Dept. of CSE,AMCEC 15CSL47 Page 28


Design and Analysis of Algorithm Laboratory

long t1=System.nanoTime();
divide(a,0,n-1);
long t2=System.nanoTime();
System.out.println("***sorted list***");
for(i=0;i<n;i++)
{
System.out.print(" "+a[i]);
}
System.out.println();
System.out.println("Time taken= "+(t2-t1));
}
}

Dept. of CSE,AMCEC 15CSL47 Page 29


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.lang.*;
import java.util.*;
import java.util.concurrent.*;

public class Mgsort


{
public static void divide(int a[],int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
divide(a,low,mid);
divide(a,mid+1,high);
merge(a,low,mid,high);

}
}
public static void merge(int a[],int low,int mid,int high)
{
int i=low,j=mid+1,k=low;
int b[]=new int[5000];
while(i<=mid&&j<=high)
{
if(a[i]<a[j])
{
b[k++]=a[i++];
}
else
{
b[k++]=a[j++];

}
}
while(i<=mid)
{
b[k++]=a[i++];

Dept. of CSE,AMCEC 15CSL47 Page 30


Design and Analysis of Algorithm Laboratory

while(j<=high)
{
b[k++]=a[j++];
}
for(k=low;k<=high;k++)
{
a[k]=b[k];
}
}

public static void main(String[] args)


{
int n,i;
int a[]=new int[5000];
Scanner read=new Scanner(System.in);
Random rand=new Random();
System.out.println("Enter n");
n=read.nextInt();
for(i=0;i<n;i++)
{
a[i]=rand.nextInt(1000);
System.out.print(" "+a[i]);
}
System.out.println();
long t1=System.nanoTime();
divide(a,0,n-1);
long t2=System.nanoTime();
System.out.println("***** SORTED LIST ****");
for(i=0;i<n;i++)
{
System.out.print(" "+a[i]);
}
System.out.println();
double t3=(t2-t1);
System.out.println("TIME TAKEN FOR THE MERGE SORT in nano sec="+t3);
double sec=(double)t3/10000000000.0;
System.out.println("Which is " + sec + " Seconds");

Dept. of CSE,AMCEC 15CSL47 Page 31


Design and Analysis of Algorithm Laboratory

Output:

Enter n
5
817 289 189 368 104
***** SORTED LIST ****
104 189 289 368 817
TIME TAKEN FOR THE MERGE SORT in nano sec=30792.0
Which is 3.0792E-6 Seconds

Enter n
10
971 683 294 547 617 852 532 340 359 386
***** SORTED LIST ****
294 340 359 386 532 547 617 683 852 971
TIME TAKEN FOR THE MERGE SORT in nano sec=59363.0
Which is 5.9363E-6 Seconds

OR
package mgsortb2;
import java.lang.*;
import java.util.*;

public class Mgsortb2


{
public static void divide(int a[],int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
divide(a,low,mid);
divide(a,mid+1,high);
merge(a,low,mid,high);

}
}
public static void merge(int a[],int low,int mid,int high)
{
int i=low,j=mid+1,k=low;
int b[]=new int[5000];
while(i<=mid&&j<=high)
{
if(a[i]<a[j])
{
b[k++]=a[i++];

Dept. of CSE,AMCEC 15CSL47 Page 32


Design and Analysis of Algorithm Laboratory

}
else
{
b[k++]=a[j++];

}
}
while(i<=mid)
{
b[k++]=a[i++];

}
while(j<=high)
{
b[k++]=a[j++];
}
for(k=low;k<=high;k++)
{
a[k]=b[k];
}
}

public static void main(String[] args)


{
int n,i;
int a[]=new int[5000];
Scanner read=new Scanner(System.in);
Random rand=new Random();
System.out.println("Enter n");
n=read.nextInt();
for(i=0;i<n;i++)
{
a[i]=rand.nextInt(1000);
System.out.print(" "+a[i]);
}
System.out.println();
long t1=System.currentTimeMillis();
divide(a,0,n-1);
long t2=System.currentTimeMillis();
System.out.println("***** SORTED LIST ****");
for(i=0;i<n;i++)
{
System.out.print(" "+a[i]);
}

Dept. of CSE,AMCEC 15CSL47 Page 33


Design and Analysis of Algorithm Laboratory

System.out.println();
System.out.println("TIME TAKEN FOR THE MERGE SORT="+(t2-t1));

Dept. of CSE,AMCEC 15CSL47 Page 34


Design and Analysis of Algorithm Laboratory

6. Implement in Java, the 0/1 Knapsack problem using: a. Dynamic Programming method
import java.lang.*;
import java.util.*;

public class KNAPSACKB {


int n,m;
int w[]=new int[10];
int p[]=new int[10];
int v[][]=new int[10][10];
void getdata()
{
Scanner read=new Scanner(System.in);
System.out.println("Enter number of items");
n=read.nextInt();
System.out.println("Enter weight of each item");
for(int i=1;i<=n;i++)
{
w[i]=read.nextInt();
}
System.out.println("Enter profit of each item");
for(int i=1;i<=n;i++)
{
p[i]=read.nextInt();
}
System.out.println("Enter maximum capacity");
m=read.nextInt();
}
int max(int x,int y)
{
if(x>y)
return x;
else
return y;
}
void optimal()
{
for(int i=0;i<=n;i++)
{
for(int j=0;j<=m;j++)
{
if(i==0||j==0)
{
v[i][j]=0;

Dept. of CSE,AMCEC 15CSL47 Page 35


Design and Analysis of Algorithm Laboratory

else if(w[i]>j)
{
v[i][j]=v[i-1][j];
}
else
{
v[i][j]=max(v[i-1][j],p[i]+v[i-1][j-w[i]]);
}
}
}

}
void display()
{
System.out.println("* * * * * * * * * * * * *");
for(int i=0;i<=n;i++)
{
for(int j=0;j<=m;j++)
{
System.out.print(" "+v[i][j]);
}
System.out.println();
}
System.out.println("Optimal solution= "+v[n][m]);
}
public static void main(String args[])
{
KNAPSACKB ob=new KNAPSACKB();
ob.getdata();
ob.optimal();
ob.display();
}
}

output:-
Enter number of items
5
Enter weight of each item
2
3
1
4
2
Enter profit of each item
20

Dept. of CSE,AMCEC 15CSL47 Page 36


Design and Analysis of Algorithm Laboratory

40
15
30
25
Enter maximum capacity
6
*************
0000000
0 0 20 20 20 20 20
0 0 20 40 40 60 60
0 15 20 40 55 60 75
0 15 20 40 55 60 75
0 15 25 40 55 65 80
Optimal solution= 80

6b.0/1 Knapsack problem using Greedy method


import java.lang.*;
import java.util.*;
public class Knapsack
{
int n;
float m,sum;
float w[]=new float[10];
float p[]= new float[10];
float x[]=new float [10];
void getdata()
{
Scanner read=new Scanner(System.in);
System.out.println("enter the number of items");
n=read.nextInt();
System.out.println("enter item with decsending order density");
System.out.println("enter the weight of each item");
for(int i=0;i<n;i++)
{
w[i]=read.nextFloat();

}
System.out.println("enter profit of each item");
for(int i=0;i<n;i++)
{
p[i]=read.nextFloat();

}
System.out.println("enter max capacity");

Dept. of CSE,AMCEC 15CSL47 Page 37


Design and Analysis of Algorithm Laboratory

m=read.nextFloat();
}
void optimal()
{
int i;
float rem;
for( i=1;i<n;i++)
{
x[i]=0;

rem=m; sum=0;
for(i=0;i<n;i++)
{
if(w[i]>rem)
break;
x[i]=1;
sum=sum+p[i];
rem=rem-w[i];

}
if(i<=n)
{
x[i]=rem/w[i];
sum=sum+(rem/w[i]*p[i]);

}
}
void display()
{
System.out.println("optimal sloution="+sum);
System.out.println("item selected weight and profit");
for(int i=1;i<n;i++)
{
System.out.print(x[i]*w[i]);
System.out.print(" "+x[i]*p[i]);
System.out.println();

}
}

Dept. of CSE,AMCEC 15CSL47 Page 38


Design and Analysis of Algorithm Laboratory

public static void main(String[] args)


{
Knapsack ob=new Knapsack();
ob.getdata();
ob.optimal();
ob.display();

Output:
Enter the number of items
4
enter item with decsending order density
enter the weight of each item
10
12
13
14
enter profit of each item
20
22
25
36
enter max capacity
40
optimal sloution=79.85715
item selected weight and profit
12.0 22.0
13.0 25.0
5.0 12.857143
BUILD SUCCESSFUL (total time: 28 seconds)

OR

import java.lang.*;
import java.util.*;
public class KNAPSACK8
{
int n,i;
float m,sum;
float W[]=new float[10];
float P[]=new float[10];

Dept. of CSE,AMCEC 15CSL47 Page 39


Design and Analysis of Algorithm Laboratory

float x[]=new float[10];


void getdata()
{
Scanner read=new Scanner(System.in);
System.out.println("Enter number of items");
n=read.nextInt();
System.out.println("Enter item descending order by density");
System.out.println("Enter weight of each item");
for(i=1;i<=n;i++)
{
W[i]=read.nextFloat();
}
System.out.println("Enter profit of each item");
for(int i=1;i<=n;i++)
{
P[i]=read.nextFloat();
}
System.out.println("Enter the maximum capacity");
m=read.nextFloat();
}
void optimal()
{
float rem;
for(i=1;i<=n;i++)
{
x[i]=0;
}
rem=m;
sum=0;
for(i=1;i<=n;i++)
{
if(W[i]>rem)
break;
x[i]=1;
sum=sum+P[i];
rem=rem-W[i];
}
if(i<=n)
{
x[i]=rem/W[i];
sum=sum+(rem/W[i]*P[i]);
}

}
void display()

Dept. of CSE,AMCEC 15CSL47 Page 40


Design and Analysis of Algorithm Laboratory

{
System.out.println("Optimal solution="+sum);
System.out.println("Item selected with weight-profit");
for(i=1;i<=n;i++)
{
System.out.println(x[i]*W[i]+" "+x[i]*P[i]);
}
}
public static void main(String args[])
{
KNAPSACK8 ob=new KNAPSACK8();
ob.getdata();
ob.optimal();
ob.display();
}
}

output:-
Enter number of items
5
Enter item descending order by density
Enter weight of each item
3
2
5
6
8
Enter profit of each item
8
4
8
6
2
Enter the maximum capacity
12
Optimal solution=22.0
Item selected with weight-profit
3.0 8.0
2.0 4.0
5.0 8.0
2.0 2.0
0.0 0.0

Dept. of CSE,AMCEC 15CSL47 Page 41


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 DijkstraDemoo
{
public static int min(int a,int b)
{
if(a<b)
return a;
else
return b;
}
public static boolean check(int[] v,int n)
{
for(int i=1;i<n+1;i++)
{
if(v[i]!=1)
return
true;
}
return false;
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("enter the number of nodes in graph");
int n=s.nextInt();
int i,j;
int graph[][]=new int[n+1][n+1];
int visited[]=new int[n+1];
int d[]=new int[n+1];
TreeMap<Integer,Integer> map=new TreeMap<Integer,Integer>();
System.out.println("enter cost adajency matrix for graph,if 2 nodes are not connected enter
999");
for(i=1;i<n+1;i++)
{
for(j=1;j<n+1;j++)
graph[i][j]=s.nextInt();
}
for(i=1;i<n+1;i++)
{
visited[i]=0;
d[i]=999;
}
System.out.println("enter the source vertsx");

Dept. of CSE,AMCEC 15CSL47 Page 42


Design and Analysis of Algorithm Laboratory

int source=s.nextInt();
visited[source]=1;
d[source]=0;
int u=source;
int v,a=0;
do
{
for(v=1;v<n+1;v++)
{
if(graph[u][v]!=999 && visited[v]!=1 && graph[u][v]!=0)
{
d[v]=min(d[v],(d[u]+graph[u][v]));
map.put(d[v],v);
}
}
u=map.firstEntry().getValue();
visited[u]=1;
map.clear();;
}
while(check(visited,n));
for(i=1;i<n+1;i++)
System.out.println("distance from source to "+i+" is"+d[i]);
}
}

run:
enter the number of nodes in graph
6
enter cost adajency matrix for graph,if 2 nodes are not connected enter 999
0 9 7 7 999 1
9 0 999 2 9 3
7 999 0 3 6 999
7 2 3 0 10 999
999 9 6 10 0 7
1 3 999 999 7 0
enter the source vertsx
1
distance from source to 1 is0
distance from source to 2 is4
distance from source to 3 is7
distance from source to 4 is6
distance from source to 5 is8
distance from source to 6 is1

Dept. of CSE,AMCEC 15CSL47 Page 43


Design and Analysis of Algorithm Laboratory

OR

import java.lang.*;
import java.util.*;

public class Dijkstra


{
int n; int source;
int d[][]=new int[10][10];
int path[]=new int [10];
int visited[]=new int [10];

void getdata()
{
Scanner read=new Scanner(System.in);
System.out.println("enter the number of nodes");
n=read.nextInt();
System.out.println("enter the cost matrix");

for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
d[i][j]=read.nextInt();

}
}
System.out.println("enter the source");
source=read.nextInt();

for(int i=0;i<n;i++)
{
visited[i]=0;
}

}
void shortest()
{
int i,j,u=0,v=0,min;
for(i=0;i<n;i++)
{
path[i]=d[source][i];

Dept. of CSE,AMCEC 15CSL47 Page 44


Design and Analysis of Algorithm Laboratory

visited[source]=1;
for(i=1;i<n;i++)
{
min=999;
for(j=1;j<n;j++)
{
if(path[i]<min && visited[j]==0)
{
min=path[j];
u=j;

}
}
visited[u]=1;
for(v=0;v<n;v++)
{
if(path[u]+d[u][v]<path[v]&&visited[v]==0)
{
path[v]=path[u]+d[u][v];

}
}
}
void display()
{
System.out.println("*** Shortest path***");
for(int i=0;i<n;i++)
{
System.out.println(source+"-"+i+"="+path[i]);

}
}
public static void main(String[] args)
{
Dijkstra ob=new Dijkstra();
ob.getdata();
ob.shortest();
ob.display();

Dept. of CSE,AMCEC 15CSL47 Page 45


Design and Analysis of Algorithm Laboratory

Output:
Enter the number of nodes
6
enter the cost matrix
0 9 7 7 999 1

9 0 999 2 9 3
7 999 0 3 6 999
7 2 3 0 10 999
999 9 6 10 0 7
1 3 999 999 7 0
enter the source
1
*** Shortest path***
1-0=4
1-1=0
1-2=5
1-3=2
1-4=9
1-5=3

Dept. of CSE,AMCEC 15CSL47 Page 46


Design and Analysis of Algorithm Laboratory

8. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's
algorithm. Use Union-Find algorithms in your program.

package krush;
import java.lang.*;
import java.util.*;

public class KRUSH


{
int n,ne,sum;
int d[][]=new int [10][10];
int parent[] = new int[10];
void getdata()
{
Scanner read = new Scanner(System.in);
System.out.println("Enter the number nodes");
n=read.nextInt();
System.out.println("Enter cost matrix");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
d[i][j]=read.nextInt();
}
}
for(int i=0;i<n;i++)
{
parent[i]=i;
}
}
void spantree()
{
int i,j,u=0,v=0,min;
int ne=0,sum=0;
while(ne!=n-1)
{
min=999;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(d[i][j]<min)
{
min=d[i][j];
u = i;

Dept. of CSE,AMCEC 15CSL47 Page 47


Design and Analysis of Algorithm Laboratory

v = j;
}
}
}
if(find(u)!=find(v))
{
System.out.println(u+"-"+v+"="+d[u][v]);
parent[v]=u;
ne++;
sum=d[u][v]+sum;
}
d[u][v]=d[v][u]=999;
}
System.out.println("minmum spanning tree cost="+ sum);
}
int find (int x)
{
while(x!=parent[x])
{
x=parent[x];
}
return x;
}

public static void main(String[] args)


{
KRUSH ob = new KRUSH();
ob.getdata();
System.out.println("******** minimum spanning tree ********");
ob.spantree();
}

output:
Enter the number nodes
6
Enter cost matrix
0 35 999 30 999 999
35 0 10 38 90 999
999 10 0 999 40 50
30 38 999 0 20 999
999 90 40 20 0 45
999 999 50 999 45 0
******** minimum spanning tree ********

Dept. of CSE,AMCEC 15CSL47 Page 48


Design and Analysis of Algorithm Laboratory

1-2=10
3-4=20
0-3=30
0-1=35
4-5=45
minmum spanning tree cost=140

Dept. of CSE,AMCEC 15CSL47 Page 49


Design and Analysis of Algorithm Laboratory

9. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.

import java.lang.*;
import java.util.*;
public class PRIMSA
{
int n,ne,sum;
int d[][]=new int[10][10];
int visited[]=new int[10];
void getdata()
{
int i,j;
Scanner read=new Scanner(System.in);
System.out.println("Enter number of nodes");
n=read.nextInt();
System.out.println("Enter cost matrix");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
d[i][j]=read.nextInt();
}
}
for(i=0;i<n;i++)
{
visited[i]=0;
}
}
void spantree()
{
int i,j,u=0,v=0,min;
ne=0;
sum=0;
visited[0]=1;
while(ne!=n-1)
{
min=999;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(d[i][j]<min)
{
if(visited[i]==1&&visited[j]==0)
{

Dept. of CSE,AMCEC 15CSL47 Page 50


Design and Analysis of Algorithm Laboratory

min=d[i][j];
u=i;
v=j;
}
}
}
}
System.out.println(u+"---"+v+"="+d[u][v]);
ne++;
sum=sum+d[u][v];
visited[v]=1;
}
System.out.println("Cost of minimum spanning tree="+sum);
}

public static void main(String[] args)


{
PRIMSA ob=new PRIMSA();
ob.getdata();
System.out.println("Minimum Spanning Tree.......");
ob.spantree();

Output:

Enter number of nodes


4
Enter cost matrix
0 2 2 999
2 0 999 1
2 999 0 5
999 1 5 0
Minimum Spanning Tree.......
0---1=2
1---3=1
0---2=2
Cost of minimum spanning tree=5

OR

Dept. of CSE,AMCEC 15CSL47 Page 51


Design and Analysis of Algorithm Laboratory

import java.util.Scanner;
class Prim
{
public static void my_prim(int[][] adj, int N)
{
int i,j,nv,min,min_cost=0,u=0,v=0;
int[] visit=new int[N];
for(i=0;i<N;i++)
{
visit[i]=-0;
}
visit[0]=1;
nv=1;
while(nv<N)
{
min=999;
for(i=0;i<N;i++)
{
if(visit[i]==1)
{
for(j=0;j<N;j++)
{
if(adj[i][j]<min)
{
min=adj[i][j];
adj[i][j]=999;
u=i;
v=j;
}
}
}
}
if(visit[u]==1 && visit[v]==0)
{
visit[v]=1;
min_cost+=min;
nv++;
System.out.printf("Edge %d - %d: (%d)\n",u,v,min);
}
}
System.out.println("Cost:" +min_cost);
}
}
public class Prgm9
{

Dept. of CSE,AMCEC 15CSL47 Page 52


Design and Analysis of Algorithm Laboratory

public static void main(String[] arg)


{
int[][] adj;
int N,i,j,S,D;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of nodes in the graph");
N=sc.nextInt();
adj=new int[N][N];
for(i=0;i<N;i++)
for(j=0;j<N;j++)
adj[i][j]=-1;
System.out.println("Enter the adjacency matrix");
System.out.println("Enter 0 for no connection and weights for connection");
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
adj[i][j]=sc.nextInt();
if(adj[i][j]==0)
adj[i][j]=999;
}
}
Prim.my_prim(adj,N);
}
}

Enter number of nodes in the graph


4
Enter the adjacency matrix
Enter 0 for no connection and weights for connection
0220
2001
2005
0150
Edge 0 - 1: (2)
Edge 1 - 3: (1)
Edge 3 - 2: (5)
Cost:8

Dept. of CSE,AMCEC 15CSL47 Page 53


Design and Analysis of Algorithm Laboratory

10. Write Java programs to implement All-Pairs Shortest Paths problem using
a. Floyd's algorithm.

import java.lang.*;
import java.util.*;
public class FLOYD {
int n;
int D[][]=new int[5][5];
void getdata()
{
Scanner read=new Scanner(System.in);
System.out.println("Enter number of nodes");
n=read.nextInt();
System.out.println("Enter cost matrix");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
D[i][j]=read.nextInt();
}
}

}
void shortest()
{
for(int k=0;k<n;k++)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
D[i][j]=min(D[i][j],D[i][k]+D[k][j]);
}
}
}
}
void display()
{
System.out.println("*****All pair shortest path*****");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(" "+D[i][j]);
Dept. of CSE,AMCEC 15CSL47 Page 54
Design and Analysis of Algorithm Laboratory

}
System.out.println();
}
}
int min(int x,int y)
{
if(x<y)
{
return x;
}
else
{
return y;
}
}

public static void main(String args[])


{
FLOYD ob1=new FLOYD();
ob1.getdata();
ob1.shortest();
ob1.display();

output:-

Enter number of nodes


4
Enter cost matrix
0 20 70 999
999 0 30 999
999 999 0 40
50 999 999 0
*****All pair shortest path*****
0 20 50 90
120 0 30 70
90 110 0 40
50 70 100 0

Dept. of CSE,AMCEC 15CSL47 Page 55


Design and Analysis of Algorithm Laboratory

10 b. Implement Travelling Sales Person problem using Dynamic programming.

import java.util.Scanner;

public class TSP1


{
int n,sum;
int d[][]=new int[10][10];
int visited[]=new int[10];
void getdata()
{
Scanner read=new Scanner(System.in);
System.out.println("enter no of nodes");
n=read.nextInt();
System.out.println("enter cost matrix");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
d[i][j]=read.nextInt();
}
}
for(int i=0;i<n;i++)
{
visited[i]=0;
}
}
void travel(int u)
{
int i,v;
visited[u]=1;
System.out.print(u+"---->");
v=nearest(u);
if(v==-1)
{
System.out.println(0);
sum=sum+d[u][0];
return;
}
sum=sum+d[u][v];
travel(v);
}
int nearest(int u)
{
int i,v=-1;

Dept. of CSE,AMCEC 15CSL47 Page 56


Design and Analysis of Algorithm Laboratory

int min=999;
for(i=0;i<n;i++)
{
if(d[u][i]<min && visited[i]==0)
{
min=d[u][i];
v=i;
}
}
return v;

}
void display()
{
System.out.println("cost of tsp="+sum);
}

public static void main(String[] args)


{
TSP1 ob=new TSP1();
ob.getdata();
ob.travel(0);
ob.display();
}

OUTPUT:
enter no of nodes
4
enter cost matrix
0 30 10 90
30 0 100 20
10 100 0 5
90 20 5 0
TSP path..........
0---->2---->3---->1---->0
cost of tsp=65

OR
import java.util.Scanner;
public class MyTSP1
{
static int MAXVERT=10;
static int MAXSUBSET=1024;

Dept. of CSE,AMCEC 15CSL47 Page 57


Design and Analysis of Algorithm Laboratory

static int INF=10000;


static void printpath(int[][] vertex,int set,int nvert)
{
int i=0;
System.out.printf("1-->");
while(set!=0)
{
i=vertex[i][set];
System.out.printf("%d-->",i+1);
set=set^1<<nvert-i-1;
}
System.out.printf("1\n");
}
static int TSP(int n,int[][] mat)
{
int c,i,j,set=(1<<(n-1))-1;
int[][] table=new int[MAXVERT][MAXSUBSET];
int[][] vertex=new int[MAXVERT][MAXSUBSET];
for(i=0;i<MAXVERT;i++)
for(j=0;j<MAXSUBSET;j++)
table[i][j]=0;
for(i=0;i<n;i++)
table[i][0]=mat[i][0];
c=tsp(0,set,mat,table,vertex,n);
System.out.printf("The path is");
printpath(vertex,set,n);
return c;
}
static int tsp(int n,int set,int[][] mat,int[][] table,int[][] vertex,int nvert)
{
int i,min,temp;
if(table[n][set]==0)
{
min=INF;
for(i=0;i<nvert;i++)
{
if((set&1<<nvert-i-1)!=0)
{
temp=mat[n][i]+tsp(i,set^1<<nvert-i-1,mat,table,vertex,nvert);
if(temp<min)
{
min=temp;
vertex[n][set]=i;
}
}

Dept. of CSE,AMCEC 15CSL47 Page 58


Design and Analysis of Algorithm Laboratory

}
table[n][set]=min;
}
return table[n][set];
}
public static void main(String args[])
{
int i,j;
int[][] mat=new int[MAXVERT][MAXVERT];
Scanner sc=new Scanner(System.in);
System.out.printf("Enter the number of vertices :\n");
MAXVERT=sc.nextInt();
System.out.printf("Enter cost matrix :\n");
for(i=0;i<MAXVERT;i++)
for(j=0;j<MAXVERT;j++)
mat[i][j]=sc.nextInt();
System.out.printf("The minimum cost is %d \n",TSP(MAXVERT,mat));
return;
}
}

OUTPUT:-

Enter the number of vertices :


4
Enter cost matrix :
0124
1 0 999 1
2 999 0 1
4110
The path is1-->2-->4-->3-->1
The minimum cost is 5

Dept. of CSE,AMCEC 15CSL47 Page 59


Design and Analysis of Algorithm Laboratory

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

import java.util.Scanner;
class subset
{
int s[],x[];
int d,n;
subset()
{
s=new int[10];
x=new int[10];
}
void read()
{
int sum=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter the total number of elements in set");
n=in.nextInt();
System.out.println("Enter the set");
for(int i=1;i<=n;i++)
s[i]=in.nextInt();
System.out.println("Enter the maximum set value");
d=in.nextInt();
for(int i=1;i<=n;i++)
sum=sum+s[i];
if(sum<d)
System.out.println("The sets are");
subset_fun(0,1,sum);
in.close();
}
void subset_fun(int S,int k,int r)
{
x[k]=1;
if((S+s[k])==d)
{
for(int i=1;i<=k;i++)
if(x[i]==1)
System.out.println(+s[i]+" ");
System.out.println();
}
else
if(S+s[k]+s[k+1]<=d)

Dept. of CSE,AMCEC 15CSL47 Page 60


Design and Analysis of Algorithm Laboratory

subset_fun(S+s[k],k+1,r-s[k]);
if((S+r-s[k]>=d)&&(S+s[k+1]<=d))
{
x[k]=0;
subset_fun(S,k+1,r-s[k]);
}
}
}

public class Prgm11


{
public static void main(String[] args)
{
subset st=new subset();
st.read();
}
}

OUTPUT:-
Enter the total number of elements in set
5
Enter the set
12568
Enter the maximum set value
9

1
2
6

1
8

OR
import java.lang.*;
import java.util.*;
public class SUBSETT
{
int n,d;
int s[]=new int[10];
int visited[]=new int[10];
void getdata()
{
int i,sum=0;
Scanner read=new Scanner(System.in);

Dept. of CSE,AMCEC 15CSL47 Page 61


Design and Analysis of Algorithm Laboratory

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


n=read.nextInt();
System.out.println("enter elements");
for(i=0;i<n;i++)
{
s[i]=read.nextInt();
sum=sum+s[i];
visited[i]=0;
}
System.out.println("enter d=");
d=read.nextInt();
if(sum<d)
{
System.out.println("subset is not possible....");
}
solution(0,0,sum);
}
void solution(int w,int k,int sum)
{
int i;
visited[k]=1;
if(s[k]+w==d)
{
System.out.println("subset=");
for(i=0;i<n;i++)
{
if(visited[i]==1)
{
System.out.print(" "+s[i]);
}
}
}
else if(w+s[k]+s[k+1]<=d)
{
solution(w+s[k],k+1,sum-s[k]);
}
if(w+sum-s[k]>=d&&w+s[k+1]<=d)
{
visited[k]=0;
solution(w,k+1,sum-s[k]);
}
}
public static void main(String[] args)
{
SUBSETT ob=new SUBSETT();

Dept. of CSE,AMCEC 15CSL47 Page 62


Design and Analysis of Algorithm Laboratory

ob.getdata();

output:-
enter the number of elements
5
enter elements
12356
enter d=
8
subset=
125
subset=
26
subset=
356

Dept. of CSE,AMCEC 15CSL47 Page 63


Design and Analysis of Algorithm Laboratory

12. Design and implement the presence of Hamiltonian Cycle in an undirected Graph G of n
vertices.
import java.util.Arrays;
import java.util.Scanner;
public class hamildemo
{
int count;
int path=1;
void swap(int[] arr,int x,int y)
{
int temp=arr[x];
arr[x]=arr[y];
arr[y]=temp;
}
void permute(int[] arr,int[][] G)
{
permute(arr,0,arr.length-1,G);
}
void permute(int[] arr,int i,int n,int[][] cost)
{
int j;
if(i==n)
{
hamilcycle(arr,cost);
}
else
{
for(j=i;j<=n;j++)
{
swap(arr,i,j);
permute(arr,i+1,n,cost);
swap(arr,i,j);
}
}
}
void hamilcycle(int a[],int[][] G)
{
count=0;
for(int i=0;i<a.length-1;i++)
{
if(G[a[i]][a[i+1]]!=0)
count++;

}
if(count==a.length-1&&G[a[a.length-1]][a[0]]==1)

Dept. of CSE,AMCEC 15CSL47 Page 64


Design and Analysis of Algorithm Laboratory

{
System.out.println("Cycle No "+path+"-->");
for(int i=0;i<a.length;i++)
System.out.println(a[i]+" ");
System.out.println(a[0]);
System.out.println();
path++;
}

}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the number of nodes in graph");
int n=s.nextInt();
int graph[][]=new int[n][n];
System.out.println("Enter the adjacency matrix");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
graph[i][j]=s.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
arr[i]=i;
System.out.println("All possible Hamiltonian Cycles in graph");
new hamildemo().permute(arr,graph);
}
}

run:
Enter the number of nodes in graph
5
Enter the adjacency matrix
01011
10110
01001
11001
10110
All possible Hamiltonian Cycles in graph
Cycle No 1-->
0
1
2
4
3
0

Dept. of CSE,AMCEC 15CSL47 Page 65


Design and Analysis of Algorithm Laboratory

Cycle No 2-->
0
3
1
2
4
0

Cycle No 3-->
0
3
4
2
1
0

Cycle No 4-->
0
4
2
1
3
0

Cycle No 5-->
1
0
3
4
2
1

Cycle No 6-->
1
2
4
3
0
1

Cycle No 7-->
1
2
4

Dept. of CSE,AMCEC 15CSL47 Page 66


Design and Analysis of Algorithm Laboratory

0
3
1

Cycle No 8-->
1
3
0
4
2
1

Cycle No 9-->
2
1
0
3
4
2

Cycle No 10-->
2
1
3
0
4
2

Cycle No 11-->
2
4
0
3
1
2

Cycle No 12-->
2
4
3
0
1
2

Cycle No 13-->

Dept. of CSE,AMCEC 15CSL47 Page 67


Design and Analysis of Algorithm Laboratory

3
1
2
4
0
3

Cycle No 14-->
3
0
1
2
4
3

Cycle No 15-->
3
0
4
2
1
3

Cycle No 16-->
3
4
2
1
0
3

Cycle No 17-->
4
2
1
3
0
4

Cycle No 18-->
4
2
1
0
3

Dept. of CSE,AMCEC 15CSL47 Page 68


Design and Analysis of Algorithm Laboratory

Cycle No 19-->
4
3
0
1
2
4

Cycle No 20-->
4
0
3
1
2
4

Dept. of CSE,AMCEC 15CSL47 Page 69


Design and Analysis of Algorithm Laboratory

CONTENT BEYOND THE SYLLABUS

1. GCD of Two Numbers using Recursion

public class GCD {

public static void main(String[] args) {


int n1 = 366, n2 = 60;
int hcf = hcf(n1, n2);

System.out.printf("G.C.D of %d and %d is %d.", n1, n2, hcf);


}

public static int hcf(int n1, int n2)


{
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
}

2. Java program to print a given matrix in spiral form

import java.io.*;
class GFG
{
// Function print matrix in spiral form
static void spiralPrint(int m, int n, int a[][])
{
int i, k = 0, l = 0;
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator
*/

while (k < m && l < n)


{
// Print the first row from the remaining rows
for (i = l; i < n; ++i)
{
System.out.print(a[k][i]+" ");
}

Dept. of CSE,AMCEC 15CSL47 Page 70


Design and Analysis of Algorithm Laboratory

k++;

// Print the last column from the remaining columns


for (i = k; i < m; ++i)
{
System.out.print(a[i][n-1]+" ");
}
n--;

// Print the last row from the remaining rows */


if ( k < m)
{
for (i = n-1; i >= l; --i)
{
System.out.print(a[m-1][i]+" ");
}
m--;
}

// Print the first column from the remaining columns */


if (l < n)
{
for (i = m-1; i >= k; --i)
{
System.out.print(a[i][l]+" ");
}
l++;
}
}
}

// driver program
public static void main (String[] args)
{
int R = 3;
int C = 6;
int a[][] = { {1, 2, 3, 4, 5, 6},
{7, 8, 9, 10, 11, 12},
{13, 14, 15, 16, 17, 18}
};
spiralPrint(R,C,a);
}
}

3. A Java program to check if a number is prime using inbuilt function

Dept. of CSE,AMCEC 15CSL47 Page 71


Design and Analysis of Algorithm Laboratory

import java.util.*;
import java.math.*;
class CheckPrimeTest
{
//Function to check and return prime numbers
static boolean checkPrime(long n)
{
// Converting long to BigInteger
BigInteger b = new BigInteger(String.valueOf(n));

return b.isProbablePrime(1);
}

// Driver method
public static void main (String[] args)
throws java.lang.Exception
{
long n = 13;
System.out.println(checkPrime(n));
}
}

4. Program to illustrate the Bin-Packing algorithm using next fit heuristics


import java.util.Scanner;

public class Bin_Packing_Algorithm


{
public static void binPacking(int []a, int size, int n)
{
int binCount=1;
int s = size;
for(int i=0; i<n; i++)
{
if(s - a[i] > 0)
{
s -= a[i];
continue;
}
else
{
binCount++;
s = size;
i--;
}
}

Dept. of CSE,AMCEC 15CSL47 Page 72


Design and Analysis of Algorithm Laboratory

System.out.println("Number of bins required: "+binCount);


}

public static void main(String args[])


{
System.out.println("BIN - PACKING Algorithm");
System.out.println("Enter the number of items in Set: ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("Enter "+n+" items:");
int []a = new int[n];
for(int i=0; i<n; i++)
a[i] = sc.nextInt();
System.out.println("Enter the bin size: ");
int size = sc.nextInt();
binPacking(a, size, n);
sc.close();
}
}
Output:

$ javac Bin_Packing_Algorithm.java
$ java Bin_Packing_Algorithm
BIN - PACKING Algorithm
Enter the number of items in Set:
8
Enter 8 items:
45834516
Enter the bin size:
10

Number of bins required: 5

5. A Java program for Bellman-Ford's single source shortest path algorithm.

Dept. of CSE,AMCEC 15CSL47 Page 73


Design and Analysis of Algorithm Laboratory

import java.util.*;
import java.lang.*;
import java.io.*;

// A class to represent a connected, directed and weighted graph


class Graph
{
// A class to represent a weighted edge in graph
class Edge {
int src, dest, weight;
Edge() {
src = dest = weight = 0;
}
};

int V, E;
Edge edge[];

// Creates a graph with V vertices and E edges


Graph(int v, int e)
{
V = v;
E = e;
edge = new Edge[e];
for (int i=0; i<e; ++i)
edge[i] = new Edge();
}

// The main function that finds shortest distances from src


// to all other vertices using Bellman-Ford algorithm. The
// function also detects negative weight cycle
void BellmanFord(Graph graph,int src)
{
int V = graph.V, E = graph.E;
int dist[] = new int[V];

// Step 1: Initialize distances from src to all other


// vertices as INFINITE
for (int i=0; i<V; ++i)
dist[i] = Integer.MAX_VALUE;
dist[src] = 0;

// Step 2: Relax all edges |V| - 1 times. A simple


// shortest path from src to any other vertex can
// have at-most |V| - 1 edges

Dept. of CSE,AMCEC 15CSL47 Page 74


Design and Analysis of Algorithm Laboratory

for (int i=1; i<V; ++i)


{
for (int j=0; j<E; ++j)
{
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u]!=Integer.MAX_VALUE &&
dist[u]+weight<dist[v])
dist[v]=dist[u]+weight;
}
}

// Step 3: check for negative-weight cycles. The above


// step guarantees shortest distances if graph doesn't
// contain negative weight cycle. If we get a shorter
// path, then there is a cycle.
for (int j=0; j<E; ++j)
{
int u = graph.edge[j].src;
int v = graph.edge[j].dest;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE &&
dist[u]+weight < dist[v])
System.out.println("Graph contains negative weight cycle");
}
printArr(dist, V);
}

// A utility function used to print the solution


void printArr(int dist[], int V)
{
System.out.println("Vertex Distance from Source");
for (int i=0; i<V; ++i)
System.out.println(i+"\t\t"+dist[i]);
}

// Driver method to test above function


public static void main(String[] args)
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph

Graph graph = new Graph(V, E);

Dept. of CSE,AMCEC 15CSL47 Page 75


Design and Analysis of Algorithm Laboratory

// add edge 0-1 (or A-B in above figure)


graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = -1;

// add edge 0-2 (or A-C in above figure)


graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 4;

// add edge 1-2 (or B-C in above figure)


graph.edge[2].src = 1;
graph.edge[2].dest = 2;
graph.edge[2].weight = 3;

// add edge 1-3 (or B-D in above figure)


graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 2;

// add edge 1-4 (or A-E in above figure)


graph.edge[4].src = 1;
graph.edge[4].dest = 4;
graph.edge[4].weight = 2;

// add edge 3-2 (or D-C in above figure)


graph.edge[5].src = 3;
graph.edge[5].dest = 2;
graph.edge[5].weight = 5;

// add edge 3-1 (or D-B in above figure)


graph.edge[6].src = 3;
graph.edge[6].dest = 1;
graph.edge[6].weight = 1;

// add edge 4-3 (or E-D in above figure)


graph.edge[7].src = 4;
graph.edge[7].dest = 3;
graph.edge[7].weight = -3;

graph.BellmanFord(graph, 0);
}
}

6. MULTI STAGE GRAPH

Dept. of CSE,AMCEC 15CSL47 Page 76


Design and Analysis of Algorithm Laboratory

import java.io.*;
class MultistageGraph
{
public static BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));

static int [][] G;


static int n;
static int k; //stages

public static void main (String[] args) throws IOException


{
System.out.println("\t\t\t\tMultistage Graph");

System.out.print("\nEnter the number of the vertices: ");


n = Integer.parseInt(br.readLine());
G = new int[n+1][n+1];

System.out.print("\nEnter the total number of stages in your graph: ");


k = Integer.parseInt(br.readLine());

System.out.print("\nIf there is a edge between the following vertices enter its


weight else 0:\n");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
G[i][j] = 0;
if((i!=j)&&(i<j))
{
System.out.print(i+" and "+j+": ");
G[i][j] = Integer.parseInt(br.readLine());
}
}
FGraph();
}
static void FGraph()
{
int [] cost = new int[n+1];
int [] d = new int[n+1];
int [] p = new int[k+1];
for (int i = 1; i<=n; i++)
cost[i] = 0;

for(int j=n-1; j>=1; j--)


{

Dept. of CSE,AMCEC 15CSL47 Page 77


Design and Analysis of Algorithm Laboratory

int r = findR(j+1);
cost[j] = G[j][r]+cost[r];
d[j] = r;
}

p[1] = 1; p[k] = n;
for(int j = 2; j<k; j++)
p[j] = d[p[j-1]];

System.out.print(d[1]+"-");
for(int j=2; j<=n; j++)
{
if((d[j] == d[j-1]) || (d[j] == 0))
continue;

System.out.print(d[j]+"-");
}
System.out.print(n);
}
static int findR(int cu)
{
int r1 = n+1;
for(int h =1; h<=n; h++)
{
if( (G[h][cu] != 0) && ( r1 == n+1 ) )
{
r1 = h;
continue;
}
if (G[h][cu] != 0)
{
if(G[h][cu] < G[r1][cu] )
r1 = h;
}
}
return r1;
}
}

Dept. of CSE,AMCEC 15CSL47 Page 78


Design and Analysis of Algorithm Laboratory

7. N- QUEEN PROBLEM

/* Java program to solve N Queen Problem using


backtracking */
public class NQueenProblem
{
final int N = 4;

/* A utility function to print solution */


void printSolution(int board[][])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
System.out.print(" " + board[i][j]
+ " ");
System.out.println();
}
}

/* A utility function to check if a queen can


be placed on board[row][col]. Note that this
function is called when "col" queens are already
placeed in columns from 0 to col -1. So we need
to check only left side for attacking queens */
boolean isSafe(int board[][], int row, int col)
{
int i, j;

/* Check this row on left side */


for (i = 0; i < col; i++)
if (board[row][i] == 1)
return false;

/* Check upper diagonal on left side */


for (i=row, j=col; i>=0 && j>=0; i--, j--)
if (board[i][j] == 1)
return false;

/* Check lower diagonal on left side */


for (i=row, j=col; j>=0 && i<N; i++, j--)
if (board[i][j] == 1)
return false;

return true;

Dept. of CSE,AMCEC 15CSL47 Page 79


Design and Analysis of Algorithm Laboratory

/* A recursive utility function to solve N


Queen problem */
boolean solveNQUtil(int board[][], int col)
{
/* base case: If all queens are placed
then return true */
if (col >= N)
return true;

/* Consider this column and try placing


this queen in all rows one by one */
for (int i = 0; i < N; i++)
{
/* Check if queen can be placed on
board[i][col] */
if (isSafe(board, i, col))
{
/* Place this queen in board[i][col] */
board[i][col] = 1;

/* recur to place rest of the queens */


if (solveNQUtil(board, col + 1) == true)
return true;

/* If placing queen in board[i][col]


doesn't lead to a solution then
remove queen from board[i][col] */
board[i][col] = 0; // BACKTRACK
}
}

/* If queen can not be place in any row in


this colum col, then return false */
return false;
}

/* This function solves the N Queen problem using


Backtracking. It mainly uses solveNQUtil() to
solve the problem. It returns false if queens
cannot be placed, otherwise return true and
prints placement of queens in the form of 1s.
Please note that there may be more than one
solutions, this function prints one of the

Dept. of CSE,AMCEC 15CSL47 Page 80


Design and Analysis of Algorithm Laboratory

feasible solutions.*/
boolean solveNQ()
{
int board[][] = {{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};

if (solveNQUtil(board, 0) == false)
{
System.out.print("Solution does not exist");
return false;
}

printSolution(board);
return true;
}

// driver program to test above function


public static void main(String args[])
{
NQueenProblem Queen = new NQueenProblem();
Queen.solveNQ();
}
}

Dept. of CSE,AMCEC 15CSL47 Page 81


Design and Analysis of Algorithm Laboratory

8. A Java program to implement greedy algorithm for graph coloring


import java.io.*;
import java.util.*;
import java.util.LinkedList;

// This class represents an undirected graph using adjacency list


class Graph
{
private int V; // No. of vertices
private LinkedList<Integer> adj[]; //Adjacency List

//Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}

//Function to add an edge into the graph


void addEdge(int v,int w)
{
adj[v].add(w);
adj[w].add(v); //Graph is undirected
}

// Assigns colors (starting from 0) to all vertices and


// prints the assignment of colors
void greedyColoring()
{
int result[] = new int[V];

// Initialize all vertices as unassigned


Arrays.fill(result, -1);

// Assign the first color to first vertex


result[0] = 0;

// A temporary array to store the available colors. False


// value of available[cr] would mean that the color cr is
// assigned to one of its adjacent vertices
boolean available[] = new boolean[V];

// Initially, all colors are available

Dept. of CSE,AMCEC 15CSL47 Page 82


Design and Analysis of Algorithm Laboratory

Arrays.fill(available, true);

// Assign colors to remaining V-1 vertices


for (int u = 1; u < V; u++)
{
// Process all adjacent vertices and flag their colors
// as unavailable
Iterator<Integer> it = adj[u].iterator() ;
while (it.hasNext())
{
int i = it.next();
if (result[i] != -1)
available[result[i]] = false;
}

// Find the first available color


int cr;
for (cr = 0; cr < V; cr++){
if (available[cr])
break;
}

result[u] = cr; // Assign the found color

// Reset the values back to true for the next iteration


Arrays.fill(available, true);
}

// print the result


for (int u = 0; u < V; u++)
System.out.println("Vertex " + u + " ---> Color "
+ result[u]);
}

// Driver method
public static void main(String args[])
{
Graph g1 = new Graph(5);
g1.addEdge(0, 1);
g1.addEdge(0, 2);
g1.addEdge(1, 2);
g1.addEdge(1, 3);
g1.addEdge(2, 3);
g1.addEdge(3, 4);
System.out.println("Coloring of graph 1");

Dept. of CSE,AMCEC 15CSL47 Page 83


Design and Analysis of Algorithm Laboratory

g1.greedyColoring();

System.out.println();
Graph g2 = new Graph(5);
g2.addEdge(0, 1);
g2.addEdge(0, 2);
g2.addEdge(1, 2);
g2.addEdge(1, 4);
g2.addEdge(2, 4);
g2.addEdge(4, 3);
System.out.println("Coloring of graph 2 ");
g2.greedyColoring();
}
}

9. A Java program for Floyd Warshall All Pairs Shortest Path algorithm.
import java.util.*;
import java.lang.*;
import java.io.*;

class AllPairShortestPath
{
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

Dept. of CSE,AMCEC 15CSL47 Page 84


Design and Analysis of Algorithm Laboratory

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);
}

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
int graph[][] = { {0, 5, INF, 10},

Dept. of CSE,AMCEC 15CSL47 Page 85


Design and Analysis of Algorithm Laboratory

{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}
};
AllPairShortestPath a = new AllPairShortestPath();

// Print the solution


a.floydWarshall(graph);
}
}

10. A naive recursive implementation of optimal binary search tree problem


public class GFG
{
// A recursive function to calculate cost of
// optimal binary search tree
static int optCost(int freq[], int i, int j)
{
// Base cases
if (j < i) // no elements in this subarray
return 0;
if (j == i) // one element in this subarray
return freq[i];

// Get sum of freq[i], freq[i+1], ... freq[j]


int fsum = sum(freq, i, j);

// Initialize minimum value


int min = Integer.MAX_VALUE;

// One by one consider all elements as root and


// recursively find cost of the BST, compare the
// cost with min and update min if needed
for (int r = i; r <= j; ++r)
{
int cost = optCost(freq, i, r-1) +
optCost(freq, r+1, j);
if (cost < min)
min = cost;
}

// Return minimum value


return min + fsum;
}

Dept. of CSE,AMCEC 15CSL47 Page 86


Design and Analysis of Algorithm Laboratory

// The main function that calculates minimum cost of


// a Binary Search Tree. It mainly uses optCost() to
// find the optimal cost.
static int optimalSearchTree(int keys[], int freq[], int n)
{
// Here array keys[] is assumed to be sorted in
// increasing order. If keys[] is not sorted, then
// add code to sort keys, and rearrange freq[]
// accordingly.
return optCost(freq, 0, n-1);
}

// A utility function to get sum of array elements


// freq[i] to freq[j]
static int sum(int freq[], int i, int j)
{
int s = 0;
for (int k = i; k <=j; k++)
s += freq[k];
return s;
}

// Driver code
public static void main(String[] args) {
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = keys.length;
System.out.println("Cost of Optimal BST is " +
optimalSearchTree(keys, freq, n));
}
}

Dept. of CSE,AMCEC 15CSL47 Page 87


Design and Analysis of Algorithm Laboratory

VIVA QUESTIONS
 What is an algorithm?
An algorithm is finite set of instructions that is followed, accomplishes a particular task.
All algorithms must satisfy the following criteria:
• Input
• Output
• Definiteness
• Finiteness
• Effectiveness
 Define space complexity?
The space complexity can be defined as amount of memory required by an algorithm to
run.
 Define time complexity?
The time complexity of an algorithm is the amount of time required by an algorithm to run
to completion.
 What are the desirable properties of an algorithm?
• Simplicity: designing algorithms that are simpler to understand and code.
• Generality:

 Define Worst-case, Best-case, Average case efficiencies?


Algorithm efficiency depends on the input size n.
For some algorithms efficiency depends on type of input.
We have best, worst & average case efficiencies.
• Worst-case efficiency: Efficiency (number of times the basic operation will be
executed) for the worst case input of size n. i.e. The algorithm runs the longest
among all possible inputs of size n.
• Best-case efficiency: Efficiency (number of times the basic operation will be
executed) for the best case input of size n. i.e. The algorithm runs the fastest
among all possible inputs of size n.
• Average-case efficiency: Average time taken (number of times the basic operation
will be executed) to solve all the possible instances (random) of the input.
NOTE: NOT the average of worst and best case
 Discuss Asymptotic Notations?
Asymptotic notation is a way of comparing functions that ignores constant factors and
small input sizes. Three notations used to compare orders of growth of an algorithm‘s basic
operation count are: Big Oh- O notation, Big Omega- Ω notation ,Big Theta- Θ notation.

Dept. of CSE,AMCEC 15CSL47 Page 88


Design and Analysis of Algorithm Laboratory

 Define Big Oh- O notation?


A function t(n) is said to be in O(g(n)), denoted t(n) ∈ O(g(n)), if t(n) is bounded above by
some constant multiple of g(n) for all large n, i.e., if there exist some positive constant c
and some nonnegative integer n0 such that t(n) ≤ cg(n) for all n ≥ n0

 Define Big Omega- Ω notation?


A function t (n) is said to be in Ω (g(n)), denoted t(n) ∈ Ω (g (n)), if t (n) is bounded below
by some constant multiple of g (n) for all large n, i.e., if there exist some positive constant c
and some nonnegative integer n0 such that t(n) ≥ cg(n) for all n ≥ n0

 Define Big Theta- Θ notation?


A function t (n) is said to be in Θ(g (n)), denoted t(n) ∈ Θ(g (n)), if t (n) is bounded both
above and below by some constant multiple of g (n) for all large n, i.e., if there exist some
positive constant c1 and c2 and some nonnegative integer n0 such that c2 g (n) ≤ t (n) ≤ c1
g (n) for all n ≥ n0

 Explain selection sort?


The algorithm divides the input list into two parts:
a)the sublist of items already sorted, which is built up from left to right at the front (left) of
the list, and b)the sublist of items remaining to be sorted that occupy the rest of the list.
Initially, the sorted sublist is empty and the unsorted sublist is the entire input list.
The algorithm proceeds by finding the smallest (or largest, depending on sorting order)
element in the unsorted sublist, exchanging it with the leftmost unsorted element (putting it
in sorted order), and moving the sublist boundaries one element to the right.

 Explain bubble sort?


Compare adjacent elements of the list and exchange them if they are out of order. Then we
repeat the process, By doing it repeatedly, end up bubbling up the largest element to the
last position on the list.

 What is sequential search?


The algorithm simply compares successive elements of a given list with a given search key
until either a match is encountered(successful search) or the list is exhausted without
finding a match(unsuccessful search).

 Analysis of Sequential Search Algorithm:

Best Case: The key is the first element in the array


# of comparisons of an array element to the key: 1 = O(1)

Worst Case: The key is the last element in the array or the key is not in the array
# of comparisons: n = O(n) and Θ(n)

Average Case: The key is equally likely to be in any position in the array
If the key is in the first array position: 1 comparison

Dept. of CSE,AMCEC 15CSL47 Page 89


Design and Analysis of Algorithm Laboratory

If the key is in the second array position: 2 comparisons


The average number of comparisons is (n+1)/2 = Θ(n).

 Discuss brute - force string matching?


Given a string of n characters called the text and a string of m characters (m = n) called the
pattern, find a substring of the text that matches the pattern. To put it more precisely, we
want to find i—the index of the leftmost character of the first matching substring in the text
- such that
ti = p0, . . . , ti+j = pj , . . . , ti+m-1 = pm-1:
t0 . . . ti . . . ti+j . . . ti+m-1 . . . tn-1 text T
p0 . . . pj . . . pm-1 pattern P

Pattern: happy
Text: It is never too late to have a happy childhood.

 15. Define divide and conquer?

Divide & conquer is a general algorithm design strategy with a general plan as follows:
DIVIDE: A problem‘s instance is divided into several smaller instances of the same
problem, ideally of about the same size.
RECUR: Solve the sub-problem recursively.
CONQUER: If necessary, the solutions obtained for the smaller instances are combined to
get a solution to the original instance.

 16 What are the Advantages of Divide & Conquer technique?


• For solving conceptually difficult problems like Tower Of Hanoi, divide &
conquer is a powerful tool
• Results in efficient algorithms
• Divide & Conquer algorithms are adapted foe execution in multi-processor
machines
• Results in algorithms that use memory cache efficiently.

 List the Limitations of divide & conquer technique?


• Recursion is slow
• Very simple problem may be more complicated than an iterative approach.
Example: adding n numbers etc

 Define binary tree?


Binary tree is a dichotomic divide and conquer search algorithm. Ti inspects the middle
element of the sorted list. If equal to the sought value, then the position has been found.
Otherwise, if the key is less than the middle element, do a binary search on the first half,
else on the second half. Algorithm can be implemented as recursive or non-recursive
algorithm.

Dept. of CSE,AMCEC 15CSL47 Page 90


Design and Analysis of Algorithm Laboratory

 List some Applications of binary search?


• Number guessing game
• Word lists/search dictionary etc

 What are the Advantages of binary tree?


• Efficient on very big list
• Can be implemented iteratively/recursively

 What are the Disadvantages of binary tree?


• Interacts poorly with the memory hierarchy
• Requires given list to be sorted
• Due to random access of list element, needs arrays instead of linked list.

 Analysis of binary tree


Average case efficiency: Θ ( log2 n)
Worst case efficiency: Θ ( log n)

 Define Merge sort?


• Merge sort is a sort algorithm that splits the items to be sorted into two groups,
recursively sorts each group, and merges them into a final sorted sequence.
Features:
• Is a comparison based algorithm
• Is a stable algorithm
• Is a perfect example of divide & conquer algorithm design strategy

 What are the advantages and limitations?


Advantages:
• Number of comparisons performed is nearly optimal.
• Merge sort will never degrade to O(n2)
• It can be applied to files of any size
Limitations:
• Uses O(n) additional memory.
 Define Quick sort?
Quick sort is a well –known sorting algorithm, based on divide & conquer approach. The
steps are:
• Pick an element called pivot from the list
• Reorder the list so that all elements which are less than the pivot come before the
pivot and all elements greater than pivot come after it. After this partitioning, the
pivot is in its final position. This is called the partition operation.
• Recursively sort the sub-list of lesser elements and sub-list of greater elements.
Features:
• Developed by C.A.R. Hoare
• Efficient algorithm
• NOT stable sort
• Significantly faster in practice, than other algorithms

Dept. of CSE,AMCEC 15CSL47 Page 91


Design and Analysis of Algorithm Laboratory

 Efficiency analysis of sorting algorithms


Data Time Time Time Space
Algorith
Structur Complexity Complexity Complexity Complexity
m
e : Best : Average : Worst : Worst

Quick
Array O(n log(n)) O(n log(n)) O(n^2) O(log(n))
Sort
O(n)
Merge
Array O(n log(n)) O(n log(n)) O(n log(n))
sort

Bubble
Array O(n) O(n^2) O(n^2) O(1)
sort
Insertion
Array O(n) O(n^2) O(n^2) O(1)
sort
Selection
Array O(n^2) O(n^2) O(n^2) O(1)
sort

 Define greedy technique?


Greedy technique is a general algorithm design strategy, built on following elements:
• configurations: different choices, values to find
• objective function: some configurations to be either maximized or minimized.

• Difference between Greedy method and Dynamic programming method?


• LIKE dynamic programming, greedy method solves optimization problems.
• LIKE dynamic programming, greedy method problems exhibit optimal
substructure
• UNLIKE dynamic programming, greedy method problems exhibit the greedy
choice property -avoids back-tracing.

• List some applications of the Greedy Strategy?


• Optimal solutions:
Change making
Minimum Spanning Tree (MST)
Single-source shortest paths
Huffman codes
• Approximations:
Traveling Salesman Problem (TSP)
Fractional Knapsack problem

 Define Spanning Tree?


Spanning tree is a connected acyclic sub-graph (tree) of the given graph (G) that includes
all of G‘s vertices.

Dept. of CSE,AMCEC 15CSL47 Page 92


Design and Analysis of Algorithm Laboratory

 Define Minimum Spanning Tree (MST)


MST of a weighted, connected graph G is defined as: A spanning tree of G with minimum
total weight.

 Define fringe and unseen edge in prim's algorithm?


Fringe edge: An edge which has one vertex is in partially constructed tree Ti and
the other is not.
Unseen edge: An edge with both vertices not in Ti

 Discuss the efficiency of prim's algorithm?


Efficiency of Prim‘s algorithm is based on data structure used to store priority queue.
• Unordered array: Efficiency: Θ(n2)
• Binary heap: Efficiency: Θ(m log n)
• Min-heap: For graph with n nodes and m edges: Efficiency: (n + m) log n

 State Prim's algorithm?


Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a connected
weighted undirected graph. This means it finds a subset of the edges that forms a tree that
includes every vertex, where the total weight of all the edges in the tree is minimized.

 What are the steps in Kruskal's algorithm?


STEP 1: Sort the edges by increasing weight
STEP 2: Start with a forest having |V| number of trees.
STEP 3: Number of trees are reduced by ONE at every inclusion of an edge
At each stage:
• Among the edges which are not yet included, select the one with minimum weight
AND which does not form a cycle.
• The edge will reduce the number of trees by one by combining two trees of the
forest.

 Discuss the efficiency of kruskal's algorithm?


Efficiency:
Efficiency of Kruskal‘s algorithm is based on the time needed for sorting the edge weights
of a given graph.
• With an efficient sorting algorithm: Efficiency: Θ(|E| log |E| )

 Define Shortest Path Problem?


Given a connected directed graph G with non-negative weights on the edges and a root
vertex r, find for each vertex x, a directed path P (x) from r to x so that the sum of the
weights on the edges in the path P (x) is as small as possible.

 Discuss the efficiency of Single Source Shortest Paths's algorithm?


Use unordered array to store the priority queue: Efficiency = Θ(n2)
Use min-heap to store the priority queue: Efficiency = O(m log n)

Dept. of CSE,AMCEC 15CSL47 Page 93


Design and Analysis of Algorithm Laboratory

 Define Dynamic programming


Dynamic programming (DP) is a general algorithm design technique for solving
problems with overlapping sub-problems.

• List some Dynamic Programming Properties


• An instance is solved using the solutions for smaller instances.
The solutions for a smaller instance might be needed multiple times, so store their results in
a able.
• Thus each smaller instance is solved only once.
• Additional space is used to save time.

 Difference between Dynamic Programming vs. Divide & Conquer

Divide & Conquer Dynamic Programming


Partitions a problem into independent Partitions a problem into overlapping
smaller sub-problems sub-problems
Doesn‘t store solutions of subproblems. Stores solutions of subproblems:
(Identical sub-problems may arise - thus avoids calculations of same
results in the same computations are quantity twice
performed repeatedly.)
Top down algorithms: which logically Bottom up algorithms: in which the
progresses from the initial instance smallest sub-problems are the smallest
down to the smallest sub-instances via sub-problems are results of these used
intermediate sub-instances. to construct solutions to progressively
larger sub-instances.

 What are the Rules of Dynamic Programming?


OPTIMAL SUB-STRUCTURE: An optimal solution to a problem contains optimal
solutions to sub-problems
OVERLAPPING SUB-PROBLEMS: A recursive solution contains a ―small‖ number of
distinct sub-problems repeated many times
BOTTOM UP FASHION: Computes the solution in a bottom-up fashion in the final step

 What are the three basic components of Dynamic Programming solution?


The development of a dynamic programming algorithm must have the following three
basic components:
A recurrence relation
A tabular computation
A backtracking procedure

 Define Directed graph, adjacency matrix, transitive closure?


Directed Graph: A graph whose every edge is directed is called directed graph OR
digraph
• Adjacency matrix: The adjacency matrix A = {aij} of a directed graph is the
boolean matrix that has
Dept. of CSE,AMCEC 15CSL47 Page 94
Design and Analysis of Algorithm Laboratory

 1 - if there is a directed edge from ith vertex to the jth vertex


 0 - Otherwise
• Transitive Closure: Transitive closure of a directed graph with n vertices can be
defined as the n-by-n matrix T={tij}, in which the elements in the ith row (1≤ i ≤ n)
and the jth column(1≤ j ≤ n) is 1 if there exists a nontrivial directed path (i.e., a
directed path of a positive length) from the ith vertex to the jth vertex, otherwise tij
is 0. The transitive closure provides reach ability information about a digraph.

 Floyd’s Algorithm to find -ALL PAIRS SHORTEST PATHS


Given a weighted graph G( V, Ew), the all-pairs shortest paths problem is to find the
shortest path between every pair of vertices ( vi, vj ) Є V.

 0/1 Knapsack Problem Memory function


Given a set of n items of known weights w1,…,wn and values v1,…,vn and a knapsack
of capacity W, the problem is to find the most valuable subset of the items that fit into the
knapsack. Knapsack problem is an OPTIMIZATION PROBLEM.

 what is the efficiency of knapsack problem?


• Running time of Knapsack problem using dynamic programming algorithm is: ( n *
W)
• Time needed to find the composition of an optimal solution is: O( n + W )
 What is insertion sort?
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one
item at a time.

Advantages of insertion sort.


Adaptive (i.e., efficient) for data sets that are already substantially sorted.
Stable; i.e., does not change the relative order of elements with equal keys
In-place; i.e., only requires a constant amount O(1) of additional memory space
Online; i.e., can sort a list as it receives it

Time complexity of insertion sort


Worst case: O(n2)
Best case: O(n)
Average case: O(n2)

 What is DFS & BFS?


Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data
structures. One starts at the root (selecting some node as the root in the graph case) and
explores as far as possible along each branch before backtracking.

Breadth-first search (BFS) is a strategy for searching in a graph when search is limited to
essentially two operations: (a) visit and inspect a node of a graph; (b) gain access to visit

Dept. of CSE,AMCEC 15CSL47 Page 95


Design and Analysis of Algorithm Laboratory

the nodes that neighbor the currently visited node. The BFS begins at a root node and
inspects all the neighboring nodes. Then for each of those neighbor nodes in turn, it
inspects their neighbor nodes which were unvisited, and so on.

Topological sort
A topological sort or topological ordering of a directed graph is a linear ordering of
its vertices such that for every directed edge uv from vertex u to vertex v, u comes
before v in the ordering.

Tree edge: whenever a new unvisited vertex is reached for the first time, the vertex is
attached as a child to the vertex it is being reached from with an edge called a tree edge.

Cross edge: If an edge leading to a previously visited vertex other than its immediate
predecessor is encountered, the edge is noted as a cross edge.

 Problems often used for establishing lower bounds by problem reduction


Problem Lower bound Tightness
Sorting O(n log n) yes
Searching in a sorted O(log n) yes
array
Element uniqueness O(n log n) yes
problem

 What is tractable and intractable?


Problems that can be solved in polynomial time is called tractable and problems that cannot
be solved in polynomial time is called intractable.

 Hamiltonian circuit: a path that starts and ends at the same vertex and passes through all
other vertices exactly once

 N-queens problem: the problem is to place n queens on an n-by-n chessboard so that no


two queens attack each other by being in the same row or on column or on same diagonal.

 Subset-Sum Problem: The problem of finding a subset of a given set S = {s1, ……, sn} of
n positive integers whose sum is equal to a given positive integer d.

 Travelling salesman problem: find the shortest Hamiltonian circuit in a complete graph
with positive integer

 Knapsack problem: Problem of finding the most valuable subset of n items of given
positive integer weights and values that fit into a knapsack of a given positive integer
capacity.

Dept. of CSE,AMCEC 15CSL47 Page 96

You might also like