18csl47 - Daa Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

MAHARAJA INSTITUTE OF TECHNOLOGY MYSORE

BELAWADI, SRIRANGAPATNA Taluk, MANDYA-571438


Department of Computer Science and Engineering

Design and Analysis of Algorithms


Laboratory
(18CSL47)
(2019-2020)

Prepared By
Deepthi N
Sushma Koushik N
Shashidhar S
Prasanna Patil
Divya H N
18CSL47 – DAA Lab IV-CSE

Design and Analysis of Algorithms Laboratory


Semester IV
Course Code: 18CSL47 (C247) CIE Marks:40
Number of Contact Hours/Week: 0:2:2 SEE Marks:60
Total Number of Lab Contact Hours: 36 Exam Hours:03
Course Learning Objectives
1. Design and implement various algorithms in JAVA.
2. Employ various design strategies for problem solving.
3. Measure and compare the performance of different algorithms.

CO’s DESCRIPTION OF THE OUTCOMES


C247.1 Apply the techniques of java programming and implement the same.
Implement recursive and non-recursive algorithm in a high-level
C247.2
language.
Analyse the performance of learned algorithms, data structures to solve
C247.3
given problems and document the same.
C247.4 Design algorithms using appropriate design techniques.
C247.5 Choose appropriate algorithm to solve real world problems.

Descriptions
• Design, develop, and implement the specified algorithms for the following problems
using Java language under LINUX /Windows environment. Netbeans / Eclipse or
IntelliJ Idea Community Edition IDE tool can be used for development and
demonstration.
• Installation procedure of the required software must be demonstrated, carried out
in groups and documented in the journal.

A. Traditional procedural-oriented programming languages


(such as C, Fortran, Cobol and Pascal) suffer some notable
drawbacks in creating reusable software components:
• The procedural-oriented programs are made up of
functions. Functions are less reusable. It is very difficult
to copy a function from one program and reuse in another
program because the function is likely to reference the
global variables and other functions. In other words,
functions are not well-encapsulated as a self-contained
reusable unit.
• The procedural languages are not suitable of high-level
abstraction for solving real life problems. For example, C
programs uses constructs such as if-else, for-loop, array, method, pointer, which are low-
level and hard to abstract real problems such as a Customer Relationship Management
(CRM) system or a computer soccer game.
18CSL47 – DAA Lab IV-CSE

The traditional procedural-languages separate the data structures (variables) and algorithms
(functions).
B. Object-oriented programming (OOP) languages are designed to overcome these
problems.
1. The basic unit of OOP is a class, which encapsulates both the static properties and dynamic
operations within a "box", and specifies the public interface for using these boxes. Since
classes are well encapsulated, it is easier to reuse these classes. In other words, OOP
combines the data structures and algorithms of a software entity inside the same box.
2. OOP languages permit higher level of abstraction for solving real-life problems. The
traditional procedural language (such as C and Pascal) forces you to think in terms of the
structure of the computer (e.g. memory bits and bytes, array, decision, loop) rather than
thinking in terms of the problem you are trying to solve. The OOP languages (such as Java,
C++ and C#) let you think in the problem
space, and use software objects to represent
and abstract entities of the problem space to
solve the problem.

C. Benefits of OOP
The procedural-oriented languages focus on
procedures, with function as the basic unit. You
need to first figure out all the functions and then
think about how to represent data.

The object-oriented languages focus on components that the user perceives, with objects as the
basic unit. You figure out all the objects by putting all the data and operations that describe the
user's interaction with the data.

Object-Oriented technology has many benefits:


✓ Ease in software design as you could think in the problem space rather than the machine's
bits and bytes. You are dealing with high-level concepts and abstractions. Ease in design
leads to more productive software development.
✓ Ease in software maintenance: object-oriented software is easier to understand, therefore
easier to test, debug, and maintain.
✓ Reusable software: you don't need to keep re-inventing the wheels and re-write the same
functions for different situations. The fastest and safest way of developing a new
application is to reuse existing codes - fully tested and proven codes.
Java Program Structure ( Designing & Implementing an Application)
Package Details -----------------------------------------------------import java.io.*
class className ----------------------------------------------------class Sum
{
Data Members -----------------------------------------------------int a, b, c;
User_Defined methods; ------------------------------------------void display();
public static void main(String args[])
{
Block of Statements; ---------------------------System.out.println(“Hello Java”);
}
}
➢ A package is a collection of classes, interfaces and sub-packages. A sub package contains collection of
classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and this package
is known as default package.
➢ Class is keyword used for developing user defined data type and every java program must start with a
concept of class.
➢ "ClassName" represent a java valid variable name treated as a name of the class each and every class
name in java is treated as user-defined data type.
18CSL47 – DAA Lab IV-CSE

➢ Data member represents either instance or static they will be selected based on the name of the class.
➢ User-defined methods represents either instance or static they are meant for performing the operations
either once or each and every time.
➢ Each and every java program starts execution from the main() method. And hence main() method is
known as program driver.
➢ Since main() method of java is not returning any value and hence its return type must be void.
➢ Since main() method of java executes only once throughout the java program execution and hence its
nature must be static.
➢ Since main() method must be accessed by every java programmer and hence whose access specifier
must be public.
➢ Each and every main() method of java must take array of objects of String.
➢ block of statements represents set of executable statements which are in term calling user-defined
methods are containing business-logic.
➢ The file naming conversion in the java programming is that which-ever class is containing main()
method, that class name must be given as a file name with an extension .java.
Compile and Run Java Program
Steps For compile Java Program:
➢ First Save Java program with same as class name with .java extension.
Example: Sum.java
Compile: javac Filename.java
Example, javac Sum.java
Note: Here javac is tools or application programs or exe files which is used for Compile the Java
program.
Steps For Run Java Program:
✓ For run java program use java tool.
✓ Run bY: java Filename
Example: java sum
Note: Here java is tools or application programs or exe files which is used for run the Java program.

Syllabus
1.
a. Create a Java class called Student with the following details as variables within it.
1. USN
2. Name
3.Branch
4.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.
2.
a. Design a superclass called Staff with details as StaffId, Name, Phone, Salary.
Extend this class by writing three subclasses namely Teaching (domain,
publications), Technical (skills), and Contract (period). Write a Java program to
read and display at least 3 staff objects of all three categories.
b. Write a Java class called Customer to store their name and date_of_birth. The
date_of_birth format should be dd/mm/yyyy. Write methods to read customer
data as <name, dd/mm/yyyy> and display as <name, dd, mm, yyyy> using
StringTokenizer class considering the delimiter character as “/”.
3.
a. Write a Java program to read two integers a andb. Compute a/b and print, when b
is not zero. Raise an exception when b is equal to zero.
b. Write a Java program that implements a multi-thread application that has three
threads. First thread generates a random integer for every 1 second; second thread
18CSL47 – DAA Lab IV-CSE

computes the square of the number and prints third thread will print the value of
cube of the number.
4. Sort a given set of n integer elements using Quick Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to
sort. Plot a graph of the time taken versus non graph sheet. The elements can be read
from a file or can be generated using the random number generator. Demonstrate using
Java how the divide-and-conquer method works along with its time complexity analysis:
worst case, average case and best case.
5. Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program for varied values of n> 5000 and record the time taken to
sort. Plot a graph of the time taken versus non graph sheet. The elements can be read
from a file or can be generated using the random number generator. Demonstrate using
Java how the divide-and-conquer method works along with its time complexity analysis:
worst case, average case and best case.
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 connected undirected graph using
Kruskal'salgorithm. Use Union-Find algorithms in your program.
9. Find Minimum Cost Spanning Tree of a given connected undirected graph using Prim's
algorithm.
10. Write Java programs to
a. Implement All-Pairs Shortest Paths problem using Floyd's algorithm.
b. Implement Travelling Sales Person problem using Dynamic programming.
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.
12. Design and implement in Java to find all Hamiltonian Cycles in a connected undirected
Graph G of n vertices using backtracking principle.
18CSL47 – DAA Lab IV-CSE

Program 1

1a) Create a Java class called Studentwith the following details


as variables within it.
1. USN
2. Name
3.Branch
4.Phone
Write a Java program to create nStudent objects and print the
USN, Name, Branch, and Phoneof these objects with suitable
headings

import java.util.Scanner;
class stdinfo
{
Scanner in=new Scanner(System.in);
String usn=new String();
String name=new String();
String branch=new String();
int ph;
public void read()
{
System.out.println("Enter USN,Name,Branch,Phone no.");
usn=in.next();
name=in.next();
branch=in.next();
ph=in.nextInt();
}
public void prt()
{
System.out.print(usn+"\t"+name+"\t"+branch+"\t"+ph+"\n");
}
}
class student
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of students");
int n=in.nextInt();
stdinfo[] ob=new stdinfo[n];
System.out.println("Enter the details of the
students");
for(int i=0;i<n;i++)
{ System.out.println("Student:"+(i+1));
ob[i]=new stdinfo();
ob[i].read();
}
System.out.println("Student List is:");
System.out.print("USN\tName\tBranch\tPhone no"\n");
for(int i=0;i<n;i++)
18CSL47 – DAA Lab IV-CSE

ob[i].prt();
}
}
_____________________________________________________
Output

javac student.java
java student

Enter the number of students


5
Enter the details of the students
Student:1
Enter USN,Name,Branch,Phone no.
048
Adam
CSE
343456
Student:2
Enter USN,Name,Branch,Phone no.
049
Milne
CSE
565645
Student:3
Enter USN,Name,Branch,Phone no.
056
Dijkstra
CSE
876756
Student:4
Enter USN,Name,Branch,Phone no.
069
Prim
CSE
676968
Student:5
Enter USN,Name,Branch,Phone no.
071
Floyd
CSE
987656
Student List is:
USN Name Branch Phone no
048 Adam CSE 343456
049 Milne CSE 565645
056 Dijkstra CSE 876756
069 Prim CSE 676968
071 Floyd CSE 987656
18CSL47 – DAA Lab IV-CSE

1b) Write a Java program to implement the Stack using arrays.


Write Push(), Pop(), and Display() methods to demonstrate its
working.
import java.util.Scanner;
class stack
{
static int size=3;
int s[]=new int[size];
int top=-1;
public void push(int x)
{
if(top<size-1)
s[++top]=x;
else
System.out.println("Overflow");
}
public void pop()
{
int ele;
if(top==-1)
System.out.println("Underflow");
else
{
ele=s[top--];
System.out.println("Deleted Element is"+ele);
}
}
public void dis()
{
if(top==-1)
System.out.println("Stack empty");
else
{
for(int i=0;i<=top;i++)
System.out.print(s[i]+"\t");
System.out.print("\n");
}
}
}
class stk
{
public static void main(String args[])
{
stack ob=new stack();
Scanner in=new Scanner(System.in);
System.out.println("Enter\n
1.Push\n2.Pop\n3.Display\n4.Exit");
int flag=1;
while(flag==1)
{
System.out.println("Enter Your Option");
18CSL47 – DAA Lab IV-CSE

int op=in.nextInt();
switch(op)
{
case 1: System.out.println("Enter element");
int x= in.nextInt();
ob.push(x);
break;
case 2: ob.pop();
break;
case 3: ob.dis();
break;
case 4: flag=0;
break;
default:System.out.println("Invalid Option");
}
}
}
}
Output
javac stack.java
java stk

Enter
1.Push
2.Pop
3.Display
4.Exit
Enter Your Option
1
Enter element
1
Enter Your Option
1
Enter element
2
Enter Your Option
1
Enter element
3
Enter Your Option
1
Enter element
4
Overflow
Enter Your Option
3
1 2 3
Enter Your Option
2
Deleted Element is 3
Enter Your Option
18CSL47 – DAA Lab IV-CSE

2
Deleted Element is 2
Enter Your Option
2
Deleted Element is 1
Enter Your Option
2
Underflow
Enter Your Option
3
Stack empty
Enter Your Option
4
Program 2
2a) Design a superclass called Staff with details as StaffId,
Name, Phone, Salary. Extend this class by writing three
subclasses namely Teaching (domain, publications), Technical
(skills), and Contract (period). Write a Java program to read
and display atleast 3 staffs in each category.

import java.util.*;
class staff
{
String stid=new String();
String stname=new String();
String stph=new String();
String stsal=new String();
Scanner in= new Scanner(System.in);
public void read()
{
System.out.println("Enter Staff Details(Staff ID,Name,Phone
no.and Salary)");
stid=in.nextLine();
stname=in.nextLine();
stph=in.nextLine();
stsal=in.nextLine();
}
public void display()
{
System.out.println("Staff
ID:"+stid+"\nName:"+stname+"\nPhone:"+stph+"\nSalary:"+stsal);
}
}
class teaching extends staff
{
static String tdom=new String();
static String tpbl=new String();
public void tread()
{
super.read();
18CSL47 – DAA Lab IV-CSE

System.out.println("Enter Teaching Details(Domain and


Publications)");
tdom=in.nextLine();
tpbl=in.nextLine();
}
public void tdisplay()
{
super.display();
System.out.println("Teaching Details:");
System.out.println("Domain:"+tdom+"\nPublications:"+tpbl);
}
}
class technical extends staff
{
static String skills=new String();
public void teread()
{
super.read();
System.out.println("Enter Technical Details(Skills)");
skills=in.nextLine();
}
public void tedisplay()
{
super.display();
System.out.println("Technical Details:");
System.out.println("Skills:"+skills);
}
}
class contract extends staff
{
static String con=new String();
public void cnread()
{
super.read();
System.out.println("Enter Contract Details(Period in
years)");
con=in.nextLine();
}
public void cndisplay()
{
super.display();
System.out.println("Period:"+con+"years");
}
}
class staffd
{
public static void main(String args[])
{
Scanner in= new Scanner(System.in);
teaching a[]=new teaching[10];
technical b[]=new technical[10];
18CSL47 – DAA Lab IV-CSE

contract c[]=new contract[10];


System.out.println("Enter no. of staffs");
int n=in.nextInt();
for(int i=0;i<n;i++)
{
a[i]=new teaching();
a[i].tread();
}
for(int i=0;i<n;i++)
{
b[i]=new technical();
b[i].teread();
}
for(int i=0;i<n;i++)
{
c[i]=new contract();
c[i].cnread();
}
System.out.println("Teaching Staff Details:");
for(int i=0;i<n;i++)
{
a[i].tdisplay();
}
System.out.println("Technical Staff Details:");
for(int i=0;i<n;i++)
{
b[i].tedisplay();
}
System.out.println("Contract Staff Details:");
for(int i=0;i<n;i++)
{
c[i].cndisplay();
}
}
}

Output
Enter no. of staffs
3
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
1
Adam
345678
12000
Enter Teaching Details(Domain and Publications)
ML
IEEE
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
2
Brad
234566
18CSL47 – DAA Lab IV-CSE

12000
Enter Teaching Details(Domain and Publications)
IOT
IEEE
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
3
Calvin
345678
12000
Enter Teaching Details(Domain and Publications)
AI
IEEE
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
4
David
567867
12000
Enter Technical Details(Skills)
Testing
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
5
Eris
678567
12000
Enter Technical Details(Skills)
Programming in JAVA
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
6
Fushia
345456
12000
Enter Technical Details(Skills)
ARM
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
7
Greg
765765
6000
Enter Contract Details(Period in years)
5
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
8
Hughes
987876
6000
Enter Contract Details(Period in years)
4
Enter Staff Details(Staff ID,Name,Phone no.and Salary)
9
Jack
323243
18CSL47 – DAA Lab IV-CSE

6000
Enter Contract Details(Period in years)
4
Teaching Staff Details:
Staff ID:1
Name:Adam
Phone:345678
Salary:12000
Teaching Details:
Domain:ML
Publications:IEEE
Staff Details:
Staff ID:2
Name:Brad
Phone:234566
Salary:12000
Teaching Details:
Domain:IOT
Publications:IEEE
Staff Details:
Staff ID:3
Name:Calvin
Phone:345678
Salary:12000
Teaching Details:
Domain:AI
Publications:IEEE
Technical Staff Details:
Staff ID:4
Name:David
Phone:567867
Salary:12000
Technical Details:
Skills:Testing
Staff ID:5
Name:Eris
Phone:678567
Salary:12000
Technical Details:
Skills:ARM
Staff ID:6
Name:Fushia
Phone:345456
Salary:12000
Technical Details:
Skills:ARM
Contract Staff Details:
Staff ID:7
Name:Greg
Phone:765765
Salary:6000
18CSL47 – DAA Lab IV-CSE

Contract Details:
Period:4years
Staff ID:8
Name:Hughes
Phone:987876
Salary:6000
Contract Details:
Period:4years
Staff ID:9
Name:Jack
Phone:323243
Salary:6000
Contract Details:
Period:4years

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.*;
class Customer
{
public static void main(String par[])
{
String name=new String();
Scanner in=new Scanner(System.in);
System.out.println("Enter name and DOB of customer in format
<name,dd/mm/yyyy");
name=in.nextLine();
StringTokenizer S= new StringTokenizer(name,"/");
int n=S.countTokens();
for(int i=1;i<=n&&S.hasMoreTokens();i++)
{
System.out.print(S.nextToken());
if(i<n)
System.out.print(",");
}
System.out.println();
}
}
Output
Enter name and DOB of customer in format <name,dd/mm/yyyy
Adam,12/12/2002
Adam,12,12,2002
Program 3
3a) Write a Java program to read two integers a andb. Compute
a/b and print, when b is not zero. Raise an exception when b is
equal to zero.
import java.util.*;
18CSL47 – DAA Lab IV-CSE

class Exp
{
public static void main(String par[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the value of a,b");
int a=in.nextInt();
int b=in.nextInt();
try {
int result=a/b;
System.out.println("Result = "+result);
}
catch(Exception e) {
System.out.println("Exception caught : "+e);
}
}
}
Output
1) No Exception
Enter the value of a,b
2 1
Result = 2
2) Divide by Zero
Enter the value of a,b
1 0
Exception caught : java.lang.ArithmeticException: / by
zero
______________________________________________________________
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.*;
class Firstthread extends Thread
{
Firstthread()
{
start();
}
public void run()
{
try
{
for(int i=0;i<3;i++)
{
Random r=new Random();
int n=r.nextInt(100);
System.out.println("Number = "+n);
new Secondthread(n);
new Thirdthread(n);
18CSL47 – DAA Lab IV-CSE

Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println("First thread interrupted");
}
System.out.println("First thread exiting");
}
}
class Secondthread extends Thread
{
int x;
Secondthread(int n)
{
x=n;
start();
}
public void run()
{
try
{
System.out.println(" Square = " +(x*x));
}
catch(Exception e)
{
System.out.println("Second thread interrupted");
}
System.out.println("Second thread exiting");
}
}
class Thirdthread extends Thread
{
int x;
Thirdthread(int n)
{
x=n;
start();
}
public void run()
{
try
{
System.out.println("Cube = " +(x*x*x));
}
catch(Exception e)
{
System.out.println("Third thread interrupted");
}
System.out.println("Third thread exiting");
}
18CSL47 – DAA Lab IV-CSE

}
class Mainthread
{
public static void main(String args[])
{
new Firstthread();
}
}
Output
Number = 82
Square = 6724
Second thread exiting
Cube = 551368
Third thread exiting
Number = 32
Square = 1024
Second thread exiting
Cube = 32768
Third thread exiting
Number = 66
Square = 4356
Second thread exiting
Cube = 287496
Third thread exiting
First thread exiting
Program 4
4) Sort a given set of n integer elements using Quick Sort method
and compute its time complexity. Run the program for varied
values of n> 5000 and record the time taken to sort. Plot a
graph of the time taken versus non graph sheet. The elements can
be read from a file or can be generated using the random number
generator. Demonstrate using Java how the divide-and-conquer
method works along with its time complexity analysis: worst
case, average case and best case.
import java.util.Random;
import java.util.Scanner;
class Quick
{
static int a[]=new int[10000];
static Random r=new Random();
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of elements");
int n=in.nextInt();
for(int k=0;k<n;k++)
{
a[k]=5000+r.nextInt(999);
}
System.out.println("Before Quicksort");
for(int m=0;m<n;m++)
18CSL47 – DAA Lab IV-CSE

{
System.out.print(a[m]+" ");
}
System.out.print("\n");
System.out.println("After Quicksort");
long startTime=System.nanoTime();
Qsort(a,0,n-1);
long stopTime=System.nanoTime();
long eTime=stopTime-startTime;
for(int h=0;h<n;h++)
{
System.out.print(a[h]+" ");
}
System.out.print("\n");
System.out.println("Elapsed time ="+eTime);
}
public static int part(int a[],int low,int high)
{
int j=low;
int pv=high;
int i=j-1;
int temp;
while(j<=pv)
{
while(a[j]<a[pv])
j++;
while(a[j]>a[pv])
{
i++;
temp=a[i];
a[i]=a[j];
a[j]=temp;
j++;
}
if(a[j]==a[pv])
{
i++;
temp=a[i];
a[i]=a[j];
a[j]=temp;
j++;
}
}
return i;
}
public static void Qsort(int a[],int low,int high)
{
if(low<=high)
{
int mid=part(a,low,high);
Qsort(a,0,mid-1);
18CSL47 – DAA Lab IV-CSE

Qsort(a,mid+1,high);
}
}
}
Output
Enter the number of elements
5
Before Quicksort
5263 5535 5979 5391 5620
After Quicksort
5979 5620 5535 5391 5263
Elapsed time =46896
Graph

______________________________________________________________
Program 5
5) Sort a given set of n integer elements using Merge Sort method
and compute its time complexity. Run the program for varied
values of n> 5000 and record the time taken to sort. Plot a
graph of the time taken versus non graph sheet. The elements can
be read from a file or can be generated using the random number
generator. Demonstrate using Java how the divide-and-conquer
method works along with its time complexity analysis: worst
case, average case and best case.
import java.util.*;
class merge
{
static int a[]=new int[10000];
static Random r=new Random();
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of elements");
int n=in.nextInt();
for(int k=0;k<n;k++)
{
18CSL47 – DAA Lab IV-CSE

a[k]=r.nextInt(999);
}
System.out.println("Before Mergesort");
for(int m=0;m<n;m++)
{
System.out.print(a[m]+" ");
}
System.out.print("\n");
System.out.println("After Mergesort");
long startTime=System.nanoTime();
mergesort(a,0,n-1);
long stopTime=System.nanoTime();
long eTime=stopTime-startTime;
for(int h=0;h<n;h++)
{
System.out.print(a[h]+" ");
}
System.out.print("\n");
System.out.println("Elapsed time
="+(eTime/1000000)+”ms”);
}
public static void mergesort(int a[],int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,high,mid);
}
}
public static void merge(int a[],int low,int high,int mid)
{
int i=low,j=mid+1,k=low;
int b[]=new int[10000];
while(i<=mid&&j<=high)
{
if(a[i]<a[j])
{
b[k]=a[i];
k++;i++;
}
else
{
b[k]=a[j];
k++;j++;
}
}
while(i<=mid)
{
b[k]=a[i];
18CSL47 – DAA Lab IV-CSE

k++;i++;
}
while(j<=high)
{
b[k]=a[j];
k++;j++;
}
for(i=low;i<=high;i++)
{
a[i]=b[i];
}
}
}
Output
Enter the number of elements
5
Before Mergesort
754 16 631 566 326
After Mergesort
16 326 566 631 754
Elapsed time =0 ms
Graph

______________________________________________________________
Program 6
6) Implement in Java, the 0/1 Knapsack problem using (a) Dynamic
Programming method (b) Greedy method.
(a)
import java.util.Scanner;
class KnapsackDP
{
static int wt[]=new int[10];
static int pr[]=new int[10];
public static int knapsack(int n,int m)
18CSL47 – DAA Lab IV-CSE

{
if(n==0||m==0)
return 0;
else if(wt[n]>m)
return knapsack(n-1,m);
else
return max(pr[n]+knapsack(n-1,m-wt[n]),knapsack(n-1,m));
}
public static int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter number of objects");
int n=in.nextInt();
System.out.println("Enter profit array");
for(int i=1;i<=n;i++)
pr[i]=in.nextInt();
System.out.println("Enter weight array");
for(int i=1;i<=n;i++)
wt[i]=in.nextInt();
System.out.println("Enter maximum weight");
int m=in.nextInt();
int maxpro=knapsack(n,m);
System.out.println("Maximum Profit = "+maxpro);
}
}
Output
Enter number of objects
5
Enter profit array
10 23 14 32 15
Enter weight array
2 3 1 4 1
Enter maximum weight
5
Maximum Profit = 52
(b)
import java.util.Scanner;
class KnapsackGreedy
{
static int wt[]=new int[10];
static float wp[]=new float[10];
static float twp[]=new float[10];
static int pr[]=new int[10];
static int n,curwt=0,remwt;
18CSL47 – DAA Lab IV-CSE

static float maxprofit=0,pro;


public static float knapsack(int m)
{
int i=0;
while(curwt<=m)
{
curwt+=wt[maxpro()];
maxprofit+=pr[maxpro()];
i=maxpro();
wp[maxpro()]=0;
}
curwt-=wt[i];
remwt=m-curwt;
maxprofit-=pr[i];
float newprofit=twp[i]*remwt;
maxprofit+=newprofit;
return maxprofit;
}
public static int maxpro()
{
float max=wp[1];
int index=1;
for(int i=2;i<=n;i++)
if(wp[i]>max)
{
max=wp[i];
index=i;
}
return index;
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter number of objects");
n=in.nextInt();
System.out.println("Enter profit array");
for(int i=1;i<=n;i++)
pr[i]=in.nextInt();
System.out.println("Enter weight array");
for(int i=1;i<=n;i++)
wt[i]=in.nextInt();
System.out.println("Enter maximum weight");
int m=in.nextInt();
remwt=m;
for(int i=1;i<=n;i++)
{
wp[i]=pr[i]/wt[i];
twp[i]=wp[i];
}
float maxpro=knapsack(m);
System.out.println("Maximum Profit = "+maxpro);
18CSL47 – DAA Lab IV-CSE

}
}
Output
Enter number of objects
4
Enter profit array
40 42 25 12
Enter weight array
4 7 5 3
Enter maximum weight
10
Maximum Profit = 76.0
Program 7
7) From a given vertex in a weighted connected graph, find
shortest paths to other vertices using Dijkstra's algorithm.
Write the program in Java.
import java.util.Scanner;
class Djk
{
static int n;
static int v[]=new int[10];
static int d[]=new int[10];
static int a[][]=new int[10][10];
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of nodes");
n=in.nextInt();
System.out.println("Enter the cost matrix");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
a[i][j]=in.nextInt();
System.out.println("Enter source node");
int src=in.nextInt();
dk(src);
for(int j=1;j<=n;j++)
{
if(j!=src)
System.out.println("Cost from "+src+" to "+j+" is
"+d[j]);
}
}
public static void dk(int src)
{
for(int i=1;i<=n;i++)
{
v[i]=0;
d[i]=a[src][i];
}
v[src]=1;
int x=2,m;
18CSL47 – DAA Lab IV-CSE

while(x<=n)
{
m=min();
v[m]=1;
for(int j=1;j<=n;j++)
{
if((d[m]+a[m][j]<d[j])&&(v[j]==0)&&v[j]==0&&m!=-1)
d[j]=d[m]+a[m][j];
}
x++;
}
}
public static int min()
{
int min=999,j=-1;
for(int i=1;i<=n;i++)
if(d[i]<min&&v[i]==0)
{
min=d[i];
j=i;
}
return j;
}
}
Output
Enter the number of nodes
5
Enter the cost matrix
999 3 999 7 999
3 999 4 2 999
999 4 999 5 6
7 2 5 999 4
999 999 6 4 999
Enter source node
1
Cost from 1 to 2 is 3
Cost from 1 to 3 is 7
Cost from 1 to 4 is 5
Cost from 1 to 5 is 9
Program 8
8) Find Minimum Cost Spanning Tree of a given connected
undirected graph using Kruskal's algorithm. Use Union-Find
algorithms in your program.
import java.util.Scanner;
class Krusk
{
static int n,ne=1,min=999,mincost=0;
static int parent[]=new int[11];
static int cost[][]=new int[10][10];
public static void main(String args[])
{
18CSL47 – DAA Lab IV-CSE

Scanner in=new Scanner(System.in);


System.out.println("Enter the number of nodes");
n=in.nextInt();
System.out.println("Enter the cost matrix");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cost[i][j]=in.nextInt();
krusk(cost);
}

public static void krusk(int cost[][])


{
int i,j,u=1,v=1,a=1,b=1,flag=0;
while(ne<n)
{
min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
System.out.println("Edge "+a+" to "+b+" with cost
"+cost[a][b]);
mincost=mincost+cost[a][b];
ne++;
}
cost[a][b]=cost[b][a]=999;
}
System.out.println("Total cost is = "+mincost);
}
public static boolean uni(int r,int s)
{
if(r!=s)
{
parent[s]=r;
return true;
}
return false;
}
public static int find(int i)
18CSL47 – DAA Lab IV-CSE

{
while(parent[i]!=0)
i=parent[i];
return i;
}
}
Output
Enter the number of nodes
4
Enter the cost matrix
999 4 1 1
4 999 999 3
1 999 999 2
1 3 2 999
Edge 1 to 3 with cost 1
Edge 1 to 4 with cost 1
Edge 2 to 4 with cost 3
Total cost is = 5

Program 9
9) Find Minimum Cost Spanning Tree of a given connected
undirected graph using Prim's algorithm.
import java.util.Scanner;
class Prim
{
static int n,ne=1,min=999,mincost=0;
static int visited[]=new int[11];
static int cost[][]=new int[10][10];
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of nodes");
n=in.nextInt();
System.out.println("Enter the cost matrix");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cost[i][j]=in.nextInt();
prim(cost);
}

public static void prim(int cost[][])


{
int i,j,u=1,v=1,flag=0;
while(ne<n)
{
min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
18CSL47 – DAA Lab IV-CSE

{
min=cost[i][j];
u=i;
v=j;
}
}
}
if(visited[u]==0||visited[v]==0)
{
System.out.println("Edge "+u+" to "+v+" with cost
"+cost[u][v]);
mincost=mincost+cost[u][v];
visited[v]=1;
ne++;
}
cost[u][v]=cost[v][u]=999;
}
System.out.println("Total cost is = "+mincost);
}
}
Output
Enter the number of nodes
4
Enter the cost matrix
999 4 1 1
4 999 999 3
1 999 999 2
1 3 2 999
Edge 1 to 3 with cost 1
Edge 1 to 4 with cost 1
Edge 2 to 4 with cost 3
Total cost is = 5
Program 10
10) Write Java programs to
a. Implement All-Pairs Shortest Paths problem using Floyd's
algorithm.
b. Implement Travelling Sales Person problem using Dynamic
programming.
______________________________________________________________
a)
import java.util.Scanner;
class Floyd
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int cost[][]=new int[10][10];
System.out.println("Enter the number of nodes");
int n=in.nextInt();
System.out.println("Enter the cost matrix");
for(int i=0;i<n;i++)
18CSL47 – DAA Lab IV-CSE

for(int j=0;j<n;j++)
cost[i][j]=in.nextInt();
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<n;k++)
if(cost[j][k]>cost[j][i]+cost[i][k])
cost[j][k]=cost[j][i]+cost[i][k];
System.out.println("Matrix is ");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(cost[i][j]+" ");
System.out.println();
}
}
}
Output
Enter the number of nodes
4
Enter the cost matrix
0 3 4 999
2 0 999 10
999 999 0 5
2 3 999 0
Matrix is
0 3 4 9
2 0 6 10
7 8 0 5
2 3 6 0
b)
import java.util.*;
class TSPDP
{
static int MAX=10;
static final int infinity=99;
static Scanner in=new Scanner(System.in);
public static void main(String args[])
{
int cst=infinity;
int cost[][]=new int[MAX][MAX];
int tour[]=new int[MAX];
int n;
System.out.println("Enter the number of Cities");
n=in.nextInt();
System.out.println("Enter the cost matrix");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cost[i][j]=in.nextInt();
for(int i=0;i<n;i++)
tour[i]=i;
cst=tspdp(cost,tour,0,n);
18CSL47 – DAA Lab IV-CSE

System.out.println("Cost is "+cst);
System.out.println("Tour : ");
for(int i=0;i<n;i++)
System.out.print((tour[i]+1)+ "->");
System.out.println(tour[0]+1);
in.close();
}
public static int tspdp(int cost[][],int tour[],int
start,int n)
{
int i,j,k;
int tmp[]=new int[MAX];
int mintour[]=new int[MAX];
int mincost;
int cst;
if(start==n-2)
return cost[tour[n-2]][tour[n-1]]+cost[tour[n-1]][0];
mincost=999;
for(i=start+1;i<n;i++)
{
for(j=0;j<n;j++)
tmp[j]=tour[j];
tmp[start+1]=tour[i];
tmp[i]=tour[start+1];

if(((cost[tour[start]][tour[i]])+(cst=tspdp(cost,tmp,start+1,n
)))<mincost)
{
mincost=(cost[tour[start]][tour[i]])+cst;
for(k=0;k<n;k++)
mintour[k]=tmp[k];
}
}
for(i=0;i<n;i++)
tour[i]=mintour[i];
return mincost;
}
}
Output
Enter the number of Cities
5
Enter the cost matrix
0 7 6 8 4
7 0 8 5 6
6 8 0 9 7
8 5 9 0 8
4 6 7 8 0
Cost is 30
Tour :
1->3->4->2->5->1
18CSL47 – DAA Lab IV-CSE

Program 11
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
{
public static int set[]=new int[1000];
public static int sol[]=new int[1000];
public static int sum=0,flag=0,n;
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of elements in the
set");
n=in.nextInt();
System.out.println("Enter the set ");
for(int i=0;i<n;i++)
set[i]=in.nextInt();
System.out.println("Enter the sum value ");
sum=in.nextInt();
System.out.println("The Subsets are ");
subset(set,sol,sum,0,0);
if(flag==0)
System.out.println("No Subsets found");
}
public static void subset(int set[],int sol[],int sum,int
cursum,int index)
{
if(cursum==sum)
{
for(index=0;index<n;index++)
if(sol[index]==1)
System.out.print(set[index]+" ");
System.out.println();
flag=1;
}
if(index==n)
return;
else
{
sol[index]=1;
cursum+=set[index];
subset(set,sol,sum,cursum,index+1);
sol[index]=0;
cursum-=set[index];
subset(set,sol,sum,cursum,index+1);
}
18CSL47 – DAA Lab IV-CSE

}
}
Output
Enter the number of elements in the set
5
Enter the set
1 2 5 6 8
Enter the sum value
9
The Subsets are
1 2 6
1 8
Enter the number of elements in the set
2
Enter the set
1 2
Enter the sum value
5
The Subsets are
No Subsets found
Program 12
12) Design and implement in Java to find all Hamiltonian Cycles
in a connected undirected Graph G of n vertices using
backtracking principle.
import java.util.*;
class HamiltonianCycle
{
private int adj[][],x[],n;
public HamiltonianCycle()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of nodes");
n=in.nextInt();
x=new int[n];
x[0]=0;
for (int i=1;i<n; i++)
x[i]=-1;
adj=new int[n][n];
System.out.println("Enter the adjacency matrix");
for (int i=0;i<n; i++)
for (int j=0; j<n; j++)
adj[i][j]=in.nextInt();
}

public void nextValue (int k)


{
int i=0;
while(true)
{
x[k]=x[k]+1;
18CSL47 – DAA Lab IV-CSE

if(x[k]==n)
{
x[k]=-1;
return;
}
if (adj[x[k-1]][x[k]]==1)
for (i=0; i<k; i++)
if (x[i]==x[k])
break;
if (i==k)
if (k<n-1||k==n-1&&adj[x[n-1]][0]==1)
return;
}
}
public void getHCycle(int k)
{
while(true)
{
nextValue(k);
if (x[k]==-1)
return;
if (k==n-1)
{
System.out.println("\nSolution : ");
for (int i=0; i<n; i++)
System.out.print((x[i]+1)+" ");
System.out.println(1);
}
else getHCycle(k+1);
}
}
}

class Hamiltonian
{
public static void main(String args[])
{
HamiltonianCycle obj=new HamiltonianCycle();
obj.getHCycle(1);
}
}

Output
5
Enter the adjacency matrix
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
18CSL47 – DAA Lab IV-CSE

Solution :
1 2 3 5 4 1

Solution :
1 4 5 3 2 1

(1)--(2)--(3)
| / \ |
| / \ |
| / \ |
(4)-------(5)
18CSL47 – DAA Lab IV-CSE

Expected Viva Questions.


1. What is an algorithm? What is the need for an algorithm?
2. Explain what is an algorithm in computing?
3. Explain what is Quick Sort algorithm?
4. What are Sequential and Parallel Algorithms?
5. What is Exact and Approximation algorithm?
6. What is Algorithm Design Technique?
7. Define Pseudo code.
8. What is Efficiency of algorithm?
9. What is generality of an algorithm?
10. What is algorithm’s Optimality?
11. What do you mean by ′′Worst case-Efficiency” of an algorithm?
12. What do you mean by “Amortized efficiency”?
13. Define order of growth.
14. Define Big oh notation
15. Explain divide and conquer algorithms
16. Explain Internal and External Nodes
17. Define Preorder, inorder and postorder Traversal
18. Explain about greedy technique
19. Define Spanning Tree
20. Construct a minimum spanning tree using Kruskal’s algorithm with your own example.
21. Define Dynamic Programming
22. Explain principle of Optimality
23. Explain about Multistage graphs with example.
24. Explain Backtracking
25. Define Feasible Solution
26. Explain ″Graph coloring” problem.
27. Explain the 8-Queen’s problem & discuss the possible solutions.
28. Explain what is time complexity of Algorithm?
29. Mention what are the types of Notation used for Time Complexity?
30. Explain how binary search works?
31. Explain whether it is possible to use binary search for linked lists?
32. Explain what is heap sort?
33. Explain what is Skip list?
34. Explain what is Space complexity of insertion sort algorithm?
35. Explain what a “Hash Algorithm” is and what are they used for?
36. Explain how to find whether the linked list has a loop?
37. Explain how encryption algorithm works?
38. List out some of the commonly used cryptographic algorithms?
39. Explain what is the difference between best case scenario and worst case scenario of an
algorithm?
40. Explain what is Radix Sort algorithm?
41. Explain what is a recursive algorithm?
42. Mention what are the three laws of recursion algorithm?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy