lab manual design & analysis of algorithms laboratory 18csl47...design & analysis of...

71
Design & Analysis of Algorithm [18CSL47] Dept of ISE Page 1 Lab manual Design & analysis of algorithms laboratory 18CSl47

Upload: others

Post on 04-Jun-2021

85 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 1

Lab manual

Design & analysis of algorithms

laboratory

18CSl47

Page 2: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 2

1. A. Create a Java class called Student with the following details as variables within it.

(i) USN

(ii) Name

(iii) Branch

(iv) Phone

Write a Java program to create nStudent objects and print the USN, Name, Branch, and Phoneof

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 and b. Compute a/b and print, when b is

not zero. Raise an exception when b is equal to zero.

B. Write a Java program that implements a multi-thread application that has three threads.

First thread generates a random integer for every 1 second; second thread computes the

square of the number and prints; third thread will print the value of cube of the number.

4. Sort a given set of n integer elements using Quick Sort method and compute its time

complexity. Run the program for varied values of n> 5000 and record the time taken to sort.

Plot a graph of the time taken versus 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.

Page 3: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 3

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's algorithm. 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.

AIM:

1(a) Create a Java class called Studentwith the following details as variables within it.

• USN

Page 4: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 4

• Name

• Branch

• Phone

Write a Java program to create nStudent objects and print the USN, Name, Branch,

and Phone of these objects with suitable headings.

ALGORITHM:

1. Create a stuent class with arguments to the constructor is USN, Name, Branch, Phone

2. Read the numbe of stuent objects to be created.

3. Read each student object details (USN, Name, Branch, Phone)

4. Display the USN, Name, Branch, and Phone number of each Student

PROGAM:

import java.util.Scanner;

public class Student {

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

System.out.println("Student USN is:"+stuUSN);

System.out.println("Student Name is:"+stuName);

System.out.println("Student Branch is:"+stuBranch);

System.out.println("Student Phone number is:"+stuPhone);

}

public static void main(String[] args) {

Scanner readInput = new Scanner(System.in);

System.out.println("Enter number of student objects tocreate");

int numberOfStudents = readInput.nextInt();

for(int i =1;i<=numberOfStudents;i++){

System.out.println("Enter Student USN");

String usn = readInput.next();

System.out.println("Enter Student Name");

String name = readInput.next();

System.out.println("Enter Student Branch");

String branch = readInput.next();

Page 5: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 5

System.out.println("Enter Student Phone");

String phone = readInput.next();

new Student(usn, name,branch, phone);

}

}

}

SAMPLE INPUT AND OUTPUT:

Enter number of student objects to create 1

Enter 1 Student USN 1me15cs011

Enter 1 Student Name sagar

Enter 1 Student Branch cse

Enter 1 Student Phone 9986755346

Student USN is:1me15cs011

Student Name is:sagar

Student Branch is:cse

Student Phone number is:9986755346

Page 6: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 6

Exp No: 1B Implementation of Stack using arrays Date: ……………….

AIM:

1 b. Write a Java program to implement the Stack using arrays. Write Push(), Pop(),

and Display() methods to demonstrate its working.

ALGORITHM:

Algorithm:

Stack(Max_Size)

N = Max_Size

Define a stack using array stack_array[0..N-1] of size N

top = -1

function push(data)

if(isFull())

Stack is full

else top = top + 1

stack_array[top] = data

function pop()

if(isEmpty())

Stack is empty

else

stacktop_data = stack_array[top]

top = top - 1

return stacktop_data

Page 7: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 7

function display()

if(isEmpty())

Stack is empty

else

for i=top down to 0

print array[i]

function Boolean isEmpty()

return top == -1

function Boolean isfull()

return top = N-1

PROGRAM:

import java.util.Scanner;

class stack

{

private int maxsize;

private long[] stackarray;

private int top;

public stack(int s) {

maxsize = s;

stackarray = new long[maxsize];

top = -1;

}

public void push(long j) {

stackarray[++top] = j;

}

public long pop() {

return stackarray[top--];

}

public void display(){

System.out.print("\nStack = ");

if (isempty()) {

System.out.println("Stack is Empty");

Page 8: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 8

}

else

{

for (int i = top; i >= 0; i--)

System.out.print(stackarray[i] + " ");

System.out.println();

}

}

public boolean isempty() {

return (top == -1);

}

public boolean isfull() {

return (top == maxsize-1);

}

}

class StackArray

{

public static final void main(String[] args)

{

try {

System.out.print("Size of the stack:");

Scanner s=new Scanner(System.in);

int n=s.nextInt();

stack newStack = new stack(n);

for(;;){

System.out.print("Menu\n1-Push\n2-Pop\n3-Display\n4-Exit\nEnter Your

Choice:");

int ch=s.nextInt();

switch(ch) {

case 1:

if(newStack.isfull()) {

System.out.println("Stack is full");

}

else {

Page 9: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 9

S

y

s

t

e

m

.

o

u

t

.

p

r

i

n

t

(

"

Item to be pushed:"); int

datastack=s.nextInt();

newStack.push(datastack);

}

break;

case 2:

if(newStack.isempty()) {

System.out.println("Stack is empty");

}

else {

long popeddata=newStack.pop();

System.out.println(popeddata);

}

break;

case 3: newStack.display();

break;

case 4:

break;

}

if(ch==4)

break;

}

Page 10: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 10

}catch (Exception e)

{

System.out.println(e.getMessage());

}

}

}

SAMPLE INPUT AND OUTPUT:

Size of the stack:2

Menu

1-Push

2-Pop

3-Display

4-Exit

Enter Your Choice:1

Item to be pushed:50

Menu

1-Push

2-Pop

3-Display

4-Exit

Enter Your Choice:3

Stack = 50

Menu

1-Push

2-Pop

3-Display

4-Exit

Enter Your Choice:1

Item to be pushed:80

Menu

1-Push

2-Pop

3-Display

Page 11: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 11

4-Exit

Enter Your Choice:3

Stack = 80 50

Menu

1-Push

2-Pop

3-Display

4-Exit

Enter Your Choice:2

80

Menu

1-Push

2-Pop

3-Display

4-Exit

Enter Your Choice:3

Stack = 50

Menu

1-Push

2-Pop

3-Display

4-Exit

Enter Your Choice:4

Page 12: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 12

Exp No: 2A Application using Supperclass in Java Date: ……………….

AIM:

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.

ALGORITHMS:

1. create a Super calss with the name staff and define required parameter

2. Create subcalss named Teaching and extend the super class staff facilities

3. Create subclass named Technical and extend the super class staff facilities

4. Create the subclass Contract and extend the super class facilities staff facilities

PROGRAM:

import java.util.Scanner;

class Staff

{

String name;

int staffid;

int phone;

int salary;

public Staff(int id , int no, int sal, String na){

staffid=id;

phone=no;

salary=sal;

name=na;

}

void display(){

System.out.println(" ------------------------------------ ");

System.out.println("Staff ID:"+ " "+ staffid);

Page 13: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 13

System.out.println("Staff Phone number:" + " "+ phone);

System.out.println("Staff Salary:" +" "+ salary);

System.out.println("Staff Name:" +" "+ name);

}

}

class Teaching extends Staff

{

String domain;

int no_of_publications;

public Teaching(int id, int no, int sal,String na,String d,int nop){

super(id,no,sal,na);

domain=d;

no_of_publications=nop;

}

void Tdisplay(){

System.out.println(" ------------------------------------ ");

System.out.println("Teaching Staff Details");

super.display();

System.out.println("Domain :" +" "+domain);

System.out.println("No_of_publications:"+" "+no_of_publications);

}

}

class Technical extends Staff{

String skills;

public Technical(int id , int no, int sal, String na,String sk){

super(id,no,sal,na);

skills=sk;

}

void Tedisplay(){

System.out.println(" ------------------------------------ ");

System.out.println("Technical Staff Details");

super.display();

System.out.println("Skills :" + " "+skills);

}

Page 14: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 14

}

class Contract extends Staff{

int period;

public Contract(int id , int no, int sal, String na,int pd){

super(id,no,sal,na);

period=pd;

}

void Cdisplay(){

System.out.println(" ------------------------------------ ");

System.out.println("Contract Staff Details");

super.display();

System.out.println("ContractPeriod:" + " "+period + "years");

}

}

public class multilevel{

public static void main(String args[]){

Teaching t1=new

Teaching(11,998765434,31000,"Anil","CSE",10);

Teaching t2=new Teaching(12,996655546,30000,"Anu","ISE",9);

Teaching t3=new

Teaching(13,999933442,32000,"Anusha","EEE",8);

t1.Tdisplay();

t2.Tdisplay();

t3.Tdisplay();

Technical te1=new Technical(21,994433221,22000,"Kumar","C");

Technical te2=new

Technical(22,998877665,28000,"Krisna","Java");

Technical te3=new

Technical(23,991654321,33000,"Kiran","Java");

te1.Tedisplay();

te2.Tedisplay();

te3.Tedisplay();

Contract ct1=new Contract(31,998765434,35000,"Anil",3);

Page 15: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 15

Contract ct2=new Contract(32,912345678,39000,"Meghana",2);

Contract ct3=new Contract(33,992233445,30000,"Uma",4);

ct1.Cdisplay();

ct2.Cdisplay();

ct3.Cdisplay();

}

}

SAMPLE INPUTS and OUTPUTS:

Teaching Staff Details

Staff ID: 11

Staff Phone number:

998765434 Staff Salary:

31000

Staff Name: Anil

Domain : CSE

No_of_publications

: 10

Teaching Staff Details

Staff ID: 12

Staff Phone number:

996655546 Staff Salary:

30000

Staff Name: Anu

Domain : ISE

No_of_publicatio

ns: 9

Teaching Staff Details

Page 16: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 16

Staff ID: 13

Staff Phone number:

999933442 Staff Salary:

32000

Staff Name: Anusha

Domain : EEE

No_of_publications:

8

Technical Staff Details

Staff ID: 21

Staff Phone number:

994433221 Staff Salary:

22000

Staff Name:

Kumar Skills : C

Technical Staff Details

Page 17: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 17

Staff ID: 22

Staff Phone number:

998877665 Staff Salary:

28000

Staff Name:

Krisna Skills :

Java

Technical Staff Details

Staff ID: 23

Staff Phone number:

991654321 Staff Salary:

33000

Staff Name: Kiran

Skills : Java

Contract Staff Details

Staff ID: 31

Staff Phone number:

998765434 Staff Salary:

35000

Staff Name: Anil

ContractPeriod: 3years

Contract Staff Details

Staff ID: 32

Staff Phone number:

912345678 Staff Salary:

39000

Staff Name: Meghana

Page 18: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 18

ContractPeriod: 2years

Contract Staff Details

Staff ID: 33

Staff Phone number:

992233445 Staff Salary:

30000

Staff Name: Uma

ContractPeriod: 4years

Exp No: 2B Application using String Tokenizer in Java Date: ……………….

AIM:

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 “/”.

ALGORITHMS:

1. Create a Java class Customer and define the required featueres

2. Read the date of birth in the prescribed format

3. Create a method to read the date string

4. Use StringTokenizer java class to tokenize the date string and print

PROGRAM:

import java.util.Scanner;

import java.util.StringTokenizer;

public class ReadNameDate {

public static void main(String args[]){

ReadNameDate readNameDate = new ReadNameDate();

String customerData=

readNameDate.readCustomeNameDob();

Page 19: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 19

readNameDate.displayCustomerNameDob(customerData);

}

private String readCustomeNameDob() {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter name and DOB in <name,dd/mm/yyyy>

format"); String str = scanner.next();

if(!str.startsWith("<") ||!str.endsWith(">"))

{ System.out.println("Please enter it in proper

format");

}

return str; }

private void displayCustomerNameDob(String customerData)

{ String st = customerData.substring(0,

customerData.length());

StringTokenizer stringTokenizer = new StringTokenizer(st, <,/>");

String finalString =null; while(stringTokenizer.hasMoreTokens()){

if(finalString == null){

finalString = stringTokenizer.nextToken();

}else{

}

}

finalString =finalString+","+stringTokenizer.nextToken();

System.out.println("<"+finalString+">");

}

}

SAMPLE INPUT AND OUTPUT:

Page 20: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 20

Enter name and DOB in <name,dd/mm/yyyy>

format <surya,11/12/2000>

<surya,11,12,2000>

Exp No: 3A Exceptions in Java Date: ……………….

AIM:

3 A) Write a Java program to read two integers a and b. Compute a/b and print, when b is not

zero. Raise an exception when b is equal to zero.

ALGORITHMS:

1. Read two intergers a and b

2. Compute division a/b

3. If b is not zero print the result without exception

4. If b = 0 print the exception by using Java maths exceptions

PROGRAM:

import java.util.Scanner;

public class DivideException

{

public static void main(String[] args)

{

Scanner inputDevice = new Scanner(System.in);

System.out.print("Please enter first number(numerator): ");

int numerator = inputDevice.nextInt();

System.out.print("Please enter second number(denominator): ");

int denominator = inputDevice.nextInt();

try {

new DivideException().doDivide(numerator, denominator);

}

catch (Exception e)

Page 21: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 21

{

System.out.println("Exception Condition Program is ending ");

}

}

public void doDivide(int a, int b) throws Exception

{

float result = a/b;

System.out.println("Division result of "+ a +"/"+b +"= " +result);

}

}

SAMPLE INPUT AND OUTPUT:

Please enter first number (numerator): 10

Please enter second number (denominator): 5

Division result of 10/5= 2.0

OR

Please enter first number (numerator): 10

Please enter second number(denominator): 0

Exception Condition Program is ending

Page 22: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 22

Exp No: 3B Multi-thread application using Java Date: ……………….

AIM:

2.a) Write a Java program that implements a multi-thread application that hashtree threads.

First thread generates a random integer for every 1 second; second thread computes the

square of the number and prints; third thread will print the value of cube of the number.

ALGORITHM:

1. Create a class named multithread.

2. Create three thread using thread library.

3. First thread is for generating random integer.

4. Second thread is for square of the number generated by first thread.

5. Thrid thread compute the cube of the number generated by first.

PROGRAM:

import java.util.*;

class second implements Runnable

{

public int x;

public second (int x)

{

this.x=x;

}

public void run()

{

System.out.println("Second thread:Square of the number is"+x*x);

}

}

class third implements Runnable

{

public int x;

public third(int x)

{

this.x=x;

Page 23: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 23

}

public void run()

{

System.out.println("third thread:Cube of the number is"+x*x*x);

}

}

class first extends Thread

{

public void run()

{

try int num=0;

Random r=new Random();

{

for(int i=0;i<5;i++)

{

num=r.nextInt(100);

System.out.println("first thread generated number is"+num);

Thread t2=new Thread (new second(num));

t2.start();

Thread t3=new Thread(new third(num));

t3.start();

Thread.sleep(1000);

}

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

}

}

public class multithread

{

public static void main(String args[])

Page 24: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 24

{

first a=new first();

a.start();

}

}

SAMPLE OUPUTS:

first thread generated number is77

Second thread:Square of the

number is5929 third thread:Cube of

the number is456533 first thread

generated number is76

Second thread:Square of the

number is5776 third thread:Cube of

the number is438976 first thread

generated number is14

Second thread:Square of the

number is196 third thread:Cube of

the number is2744 first thread

generated number is12

Second thread:Square of the

number is144 third thread:Cube of

the number is1728 first thread

generated number is63

Second thread:Square of the number is3969

third thread:Cube of the number is250047

Page 25: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 25

Exp No: 4 Quicksort Date: ……………….

AIM:

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

divideand-conquer method works along with its time complexity analysis: worst case,

average case and best case.

ALGORITHM:

Algorithm

Quicksort

1. function QuickSort(A[1..n], p, r)

2. if(p < r)

3. q = Parition(A[1..n], p, r)

4. QuickSort(A[1..n], p, q-1)

5. QuickSort(A[1..n], q+1, r)

6. function display()

7. for i = 1 to n

8. print A[i]

09. function Partition(A[1..n], p, r)

10. x = A[r]

11. i = p-1

12. for j = p to r - 1

13. if(A[j] <= x

14 i = i + 1

15 exchange A[i] and A[j]

16. exchange A[i+1] and A[r]

17. return i+1

Page 26: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 26

PROGRAM:

import java.util.Scanner;

import java.util.Random;

/** Generate 10 random integers in the range 0..99. */

public final class Quicksort

{

public static int heap_size;

public static final void main(String... aArgs)

{

long[] randomarray1 = new long[100000];

try {

Scanner s=new Scanner(System.in);

System.out.print("Enter N:\n");

int n=s.nextInt();

System.out.print("Enter the range:\n");

int max=s.nextInt();

int idx=1;

for(long i=max;idx<n+1;i--)

{

randomarray1[idx]=i;

idx=idx+1;

}

System.out.println("The array before sorting");

long now=System.currentTimeMillis();

QuickSort(randomarray1, 1, n);

long done=System.currentTimeMillis();

System.out.println("Quick Sort: "+(done-now));

System.out.println("Quick Sort");

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

{

System.out.println(randomarray1[i]);

Page 27: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 27

}

}catch (Exception e)

{

System.out.println(e);

}

}

private static void log(String aMessage)

{

// System.out.println(aMessage);

}

public static void QuickSort(long A[], int p, int r)

{

System.out.println(p);

System.out.println(r);

if(p < r)

{

int q = Partition(A, p, r);

QuickSort(A, p, q-1);

QuickSort(A, q+1, r);

}

}

public static int Partition(long A[], int p, int r)

{

long x = A[r];

int i = p-1;

// System.out.println(n2);

for(int j=p;j<r;j++)

{

if(A[j] <= x)

{

i = i + 1;

long temp = A[i];

A[i] = A[j];

Page 28: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 28

A[j] = temp;

}

}

long tmp = A[i+1];

A[i+1] = A[r];

A[r] = tmp;

return (i+1);

}

}

SAMPLE INPUT AND OUTPUT:

Enter the no. of elements

10

The array elements before sorting are:

144 293 51 432 348 556 333 434 200 169

***********Quick Sort Algorithm *****************

The array elements after sorting are:

51 144 169 200 293 333 348 432 434 556

The Time Complexity of Quick Sort Algorithm is:0ms

Best23

average23

worst100

Page 29: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 29

Exp No: 5 Merge Sort Date: ……………….

AIM:

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.

ALGORITHM:

Mergesort

1. function MergeSort(A[1..n], p, r)

2. if(p < r)

3. q = floor((p + r)/2 )

4. MergeSort(A[1..n], p, q)

5. MergeSort(A[1..n], q+1, r)

6. Merge(A[1..n], p, q, r)

7. function display()

8. for i = 1 to n

9. print A[i]

10. function Merge(A[1..n], p, q, r)

11. n1 = q - p + 1

12. n2 = r - q

13. Define two arrays L[1..(n1 + 1)] and R[1...(n2 + 1)]

14. for i = 1 to n1

15. L[i] = A[p + i - 1]

16. L[n1+1] = 100000000

17. for j = 1 to n2

18. R[j] = A[q + j]

19. R[n2+1] = 100000000

20 x=1

21 y=1

Page 30: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 30

22. for k = p to r

23. if(L[x] <= R[y])

24. A[k] = L[x]

25. x = x + 1

26. else

27. A[k] = R[y]

28. y = y + 1

PROGRAM:

import java.util.Scanner;

import java.util.Random;

/** Generate 10 random integers in the range 0..99. */

public final class Mergesort

{

public static int heap_size;

public static final void main(String... aArgs)

{

long[] randomarray1 = new long[100000];

try {

Scanner s=new Scanner(System.in);

System.out.print("Enter N:\n");

int n=s.nextInt();

System.out.print("Enter the range\n");

int max=s.nextInt();

int idx=1;

for(int i=max;idx<n+1;i--)

{

randomarray1[idx]=i;

idx=idx+1;

}

System.out.println("The array before sorting");

// for (idx = 1; idx < n+1; idx++)

// {

// System.out.println(randomarray1[idx]);

// }

Page 31: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 31

long now=System.currentTimeMillis();

MergeSort(randomarray1, 1, n);

long done=System.currentTimeMillis();

System.out.println("Merge Sort: "+(done-now));

System.out.println("Merge Sort");

// for(int i=1;i<=n;i++)

// {

// System.out.println(randomarray1[i]);

// }

}catch (Exception e)

{

System.out.println(e);

}

}

private static void log(String aMessage)

{

// System.out.println(aMessage);

}

public static void MergeSort(long A[], int p, int r)

{

if(p < r)

{

int q = (p+r)/2;

MergeSort(A, p, q);

MergeSort(A, q+1, r);

Merge(A, p, q, r);

}

}

public static void Merge(long A[], int p, int q, int r)

{

int n1 = q-p+1;

int n2 = r-q;

Page 32: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 32

long[] L = new long[n1+2];

long[] R = new long[n2+2];

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

{

L[i] = A[p+i-1];

}

L[n1+1] = 1000000;

for(int j=1;j<=n2;j++)

{

R[j] = A[q+j];

}

R[n2+1] = 1000000;

int x = 1;

int y = 1;

for(int k = p; k <= r; k++)

{

if(L[x] <= R[y])

{

A[k] = L[x];

x = x + 1;

}

else

{

A[k] = R[y];

y = y + 1;

}

}

}

}

Page 33: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 33

SAMPLE INPUT AND OUTPUT:

enter the size of the array

10

mergesort

values before sort

0

6

0

7

0

5

3

6

1

6

values after sort

0

0

0

1

3

5

6

6

6

7

the time taken to sort is1ms

Best23

average23

worst23

Page 34: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 34

Exp No: 6 0/1 Knapsack problem using Dynamic

Programming and Greedy method. Date: ……………….

AIM:

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

Greedy method.

a) knapsack problem-Dynamic Programming method

ALGORITHMS:

Dynamic-0-1-knapsack (v, w, n, W)

for w = 0 to W do

c[0, w] = 0

for i = 1 to n do

c[i, 0] = 0

for w = 1 to W do

if wi ≤ w then

if vi + c[i-1, w-wi] then

c[i, w] = vi + c[i-1, w-wi]

else c[i, w] = c[i-1, w]

else

c[i, w] = c[i-1, w]

PROGRAM:

package knapsack;

import java.util.Scanner;

public class knapsack_dynamic

{

static int v[][] = new int [20][20];

public static int max1(int a,int b)

Page 35: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 35

{

return(a>b)?a:b;

}

public static void main(String[] args) {

int p[] = new int[20];

int w[] = new int[20];

int i,j,n,max;

Scanner in = new Scanner (System.in);

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

n = in.nextInt();

for(i=1;i<=n;i++)

{

System.out.println(" enter the weight and profit of the item "+i);

w[i] = in.nextInt();

p[i] = in.nextInt();

}

System.out.println ("\n enter the capacity of the knapsack");

max = in.nextInt();

for(i=0;i<=n;i++)

v[i][0]=0;

for(j=0;j<=max;j++)

v[0][j]=0;

for(i=1;i<=n;i++)

for(j=1;j<=max;j++)

{

if(w[i]>j)

v[i][j]=v[i-1][j];

else

v[i][j]=max1(v[i-1][j],v[i-1][j-w[i]]+p[i]);

}

/*System.out.println ("The table is");

for(i=0;i<=n;i++)

{

Page 36: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 36

for(j=0;j<=max;j++)

System.out.println ("\t"+v[i][j]);

}*/

System.out.println ("The maximum profit is "+v[n][max]);

System.out.println ("\nThe items selected are:");

j=max;

for(i=n;i>=1;i--)

if(v[i][j]!=v[i-1][j])

{

System.out.println ("\t item:"+i);

j=j-w[i];

}

}

}

SAMPLE INPUT AND OUTPUT:

enter the number of items

5

enter the weight and profit of the item 1

Page 37: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 37

3 10

enter the weight and profit of the item 2

4 15

enter the weight and profit of the item 3

5 20

enter the weight and profit of the item 4

2 25

enter the weight and profit of the item 5

1 30

enter the capacity of the knapsack

7

The maximum profit is 70

The items selected are:

item:5

item:4

item:2

b) knapsack problem -Greedy method

ALGORITHMS:

Algorithm: Greedy-Fractional-Knapsack (w[1..n], p[1..n], W)

for i = 1 to n do x[i] = 0

weight = 0 for i = 1 to n

if weight + w[i] ≤ W

then x[i] = 1

weight = weight + w[i]

else

x[i] = (W - weight) / w[i]

weight = W

break

Page 38: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 38

return x

PROGRAM:

import java.util.Scanner;

class KObject { // Knapsack object details

float w;

float p;

float r;

}

public class KnapsackGreedy2 {

static final int MAX = 20; // max. no. of objects

static int n; // no. of objects

static float M; // capacity of Knapsack

public static void main(String args[]) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter number of objects: ");

n = scanner.nextInt();

KObject[] obj = new KObject[n];

for(int i = 0; i<n;i++)

obj[i] = new KObject();// allocate memory for members

ReadObjects(obj);

Knapsack(obj);

scanner.close();

}

static void ReadObjects(KObject obj[]) {

KObject temp = new KObject();

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the max capacity of knapsack: ");

M = scanner.nextFloat();

System.out.println("Enter Weights: ");

for (int i = 0; i < n; i++)

obj[i].w = scanner.nextFloat();

Page 39: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 39

System.out.println("Enter Profits: ");

for (int i = 0; i < n; i++)

obj[i].p = scanner.nextFloat();

for (int i = 0; i < n; i++)

obj[i].r = obj[i].p / obj[i].w;

// sort objects in descending order, based on p/w ratio

for(int i = 0; i<n-1; i++)

for(int j=0; j<n-1-i; j++)

if(obj[j].r < obj[j+1].r){

temp = obj[j];

obj[j] = obj[j+1];

obj[j+1] = temp;

}

scanner.close();

}

static void Knapsack(KObject kobj[]) {

float x[] = new float[MAX];

float totalprofit;

int i;

float U; // U place holder for M

U = M;

totalprofit = 0;

for (i = 0; i < n; i++)

x[i] = 0;

for (i = 0; i < n; i++) {

Page 40: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 40

if (kobj[i].w > U)

break;

else {

}

}

x[i] = 1;

totalprofit = totalprofit + kobj[i].p;

U = U - kobj[i].w;

System.out.println("i = " + i);

if (i < n)

x[i] = U / kobj[i].w;

totalprofit = totalprofit + (x[i] * kobj[i].p);

System.out.println("The Solution vector, x[]: ");

for (i = 0; i < n; i++)

System.out.print(x[i] + " ");

System.out.println("\nTotal profit is = " + totalprofit);

}

}

Page 41: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 41

Exp No: 7 Shortest Path using Dijkstra's algorithm Date: ……………….

AIM:

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.

ALGORITHMS:

function Dijkstra(Graph, source):

1 create vertex set Q

2 for each vertex v in Graph: // Initialization

3 dist[v] ← INFINITY // Unknown distance from source to v

4 prev[v] ← UNDEFINED //previous node in optimal path from source

5 add v to Q // All nodes initially in Q (unvisited nodes)

6 dist[source] ← 0 // Distance from source to source

7 while Q is not empty:

8 u ← vertex in Q with min dist[u]//Node with the least distance

9 // will be selected first

10 remove u from Q

12 for each neighbor v of u: // where v is still in Q.

13 alt ← dist[u] + length(u, v)

14 if alt < dist[v]: // A shorter path to v has been found

15 dist[v] ← alt

16 prev[v] ← u

17 return dist[], prev[]

PROGRAM:

Page 42: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 42

import java.util.*;

public class DijkstrasClass {

final static int MAX = 20;

final static int infinity = 9999;

static int n; // No. of vertices of G

static int a[][]; // Cost matrix

static Scanner scan = new Scanner(System.in);

public static void main(String[] args) {

ReadMatrix();

int s = 0; // starting vertex

System.out.println("Enter starting vertex: ");

s = scan.nextInt();

Dijkstras(s); // find shortest path

}

static void ReadMatrix() {

a = new int[MAX][MAX];

System.out.println("Enter the number of vertices:");

n = scan.nextInt();

System.out.println("Enter the cost adjacency matrix:");

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

for (int j = 1; j <= n; j++)

a[i][j] = scan.nextInt();

}

static void Dijkstras(int s) {

int S[] = new int[MAX];

int d[] = new int[MAX];

int u, v;

int i;

for (i = 1; i <= n; i++) {

S[i] = 0;

d[i] = a[s][i];

}

S[s] = 1;

Page 43: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 43

d[s] = 1;

i = 2;

while (i <= n) {

u = Extract_Min(S, d);

S[u] = 1;

i++;

for (v = 1; v <= n; v++) {

if (((d[u] + a[u][v] < d[v]) && (S[v] == 0)))

d[v] = d[u] + a[u][v];

}

}

for (i = 1; i <= n; i++)

if (i != s)

System.out.println(i + ":" + d[i]);

}

static int Extract_Min(int S[], int d[]) {

int i, j = 1, min;

min = infinity;

for (i = 1; i <= n; i++) {

if ((d[i] < min) && (S[i] == 0)) {

min = d[i];

j = i;

}

}

return (j);

}}

SAMPLE INPUT AND OUTPUT:

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

Enter the number of nodes:

5

Enter the cost matrix

0 3 999 7 999

Page 44: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 44

3 0 4 2 999

999 4 0 5 6

7 2 5 0 4

999 999 6 4 0

Enter the source vertex:

1

The shortest distance between

1-> 2 is :3

The shortest distance between

1-> 3 is :7

The shortest distance between

1-> 4 is :5

The shortest distance between

1-> 5 is :9

Page 45: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 45

Exp No: 8 MST using Kruskal's algorithm Date: ……………….

AIM:

Find Minimum Cost Spanning Tree of a given connected undirected graph using

Kruskal's algorithm. Use Union-Find algorithms in your program.

ALGORITHM:

KRUSKAL(G):

1 A = ∅

2 foreach v ∈ G.V:

3 MAKE-SET(v)

4 foreach (u, v) in G.E ordered by weight(u, v), increasing:

5 if FIND-SET(u) ≠ FIND-SET(v):

6 A = A ∪ {(u, v)}

7 UNION(u, v)

8 return A

PROGRAM:

package kruskal;

import java.util.Scanner;

public class kruskalpgm {

static int i,j,k,a,b,u,v,n,ne=1;

static int min,mincost=0;

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sobj=new Scanner(System.in);

int cost[][] = new int[10][10];

int parent[] = new int[10];

System.out.println("Implementation of Kruskal's algorithm");

System.out.println ("Enter the no. of vertices");

n=sobj.nextInt();

Page 46: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 46

for(i=1;i<=n;i++)

parent[i]=0;

System.out.println("\nEnter the cost adjacency matrix\n");

for(i=1;i<=n;i++)

{

for(j=1;j<=n;j++)

{

cost[i][j]=sobj.nextInt();

if(cost[i][j]==0)

cost[i][j]=999;

}

}

System.out.println("The edges of Minimum Cost Spanning Tree are");

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,parent);

v=find(v,parent);

if (uni(u,v,parent)==1)

{

System.out.println("edge("+a+","+b+")=" +min);

ne++;

Page 47: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 47

mincost +=min;

}

cost[a][b]=cost[b][a]=999;

}

System.out.println("Minimum cost = "+mincost);

}

public static int find(int i,int parent[])

{

while(parent[i]!=0)

i=parent[i];

return i;

}

public static int uni(int i,int j,int parent[])

{

if(i!=j)

{

parent[j]=i;

return 1;

}

return 0;

}

}

SAMPLE INPUT AND OUTPUT:

Implementation of Kruskal's algorithm

Enter the no. of vertices

9

Enter the cost adjacency matrix

Page 48: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 48

0 4 0 0 0 0 0 8 0

4 0 8 0 0 0 0 11 0

0 8 0 7 0 4 0 0 2

0 0 7 0 9 14 0 0 0

0 0 0 9 0 10 0 0 0

0 0 4 14 10 0 2 0 0

0 0 0 0 0 2 0 1 6

8 11 0 0 0 0 1 0 7

0 0 2 0 0 0 6 7 0

The edges of Minimum Cost Spanning Tree are

edge(7,8)=1

edge(3,9)=2

edge(6,7)=2

edge(1,2)=4

edge(3,6)=4

edge(3,4)=7

edge(1,8)=8

edge(4,5)=9

Minimum cost = 37

Page 49: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 49

Exp No: 9 MST using Prim’s algorithm Date: ……………….

AIM:

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

ALGORITHM:

MST-PRIM(G, w r)

for each u ∈ G.V

u.key = ∞

u.π = NIL

r.key = 0

Q = Q.V

while Q = φ

u = EXTRACT-MIN(Q) //minimum priority queue

for each v ∈ G.Adj(u)

v ∈ Q and w(u, v) < v.key

v.π = u

v.key = w(u, v)

PROGRAM:

package prims;

import java.util.*;

class Primss

{static int n,i,j,ne=1;

static int a,b,u,v;

public static void main (String[] args) {

int visited[] = new int[10];

int cost[][] = new int[10][10];

int min,mincost=0;

System.out.println("\n Enter the number of nodes:");

Scanner in = new Scanner (System.in);

n = in.nextInt();

Page 50: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 50

for(i=1;i<=n;i++)

visited[i]=0;

System.out.println("\n Enter the adjacency matrix:\n");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

{

cost[i][j] = in.nextInt();

if(cost[i][j]==0)

cost[i][j]=999;

}

visited[1]=1;

while(ne<n)

{

min=999;

for( i=1;i<=n;i++)

{

for( j=1;j<=n;j++)

if(cost[i][j]<min)

{

if(visited[i]!=0)

{

min=cost[i][j];

a=u=i;

b=v=j;

}

}

}

if(visited[u]==0 || visited[v]==0)

{

System.out.println(" Edge"+ne+":" +u+"," +v+ "cost:"+min);

ne++;

mincost+=min;

visited[b]=1;

Page 51: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 51

}

cost[a][b]=cost[b][a]=999;

}

System.out.println(" Minimun cost="+mincost);

}

}

SAMPLE INPUT AND OUTPUT:

Enter the number of nodes:

5

Enter the adjacency matrix:

0 5 7 0 2

5 0 0 6 3

7 0 0 4 4

0 6 4 0 5

2 3 4 5 0

Edge1:1,5cost:2

Edge2:5,2cost:3

Edge3:5,3cost:4

Edge4:3,4cost:4

Minimun cost=13

Page 52: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 52

Exp No: 10 All-Pairs Shortest Paths & Travelling Sales

Person problems

Date: ……………….

AIM:

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) Floyd's algorithm.

ALGORITHM:

1 let dist be a |V| × |V| array of minimum distances initialized to ∞ (infinity)

2 for each edge (u,v)

3 dist[u][v] ← w(u,v) // the weight of the edge (u,v)

4 for each vertex v

5 dist[v][v] ← 0

6 for k from 1 to |V|

7 for i from 1 to |V|

8 for j from 1 to |V|

9 if dist[i][j] > dist[i][k] + dist[k][j]

10 dist[i][j] ← dist[i][k] + dist[k][j]

11 end if

PROGRAM:

package pgm10;

import java.util.Scanner;

public class floydspgm {

static int cost[][] = new int[10][10];

public static void floyds(int cost[][],int n)

{

int i,j,k;

Page 53: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 53

for(k=1;k<=n;k++)

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

if(i==j)

cost[i][j]=0;

else

cost[i][j]=min(cost[i][j],cost[i][k]+cost[k][j]);

}

public static int min(int a,int b)

{

return(a<b)?a:b;

}

public static void main(String[] args) {

int n,i,j;

Scanner in = new Scanner(System.in);

System.out.println(" Enter the number of vertices:");

n=in.nextInt();

System.out.println("Enter the cost matrix");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

cost[i][j] = in.nextInt();

floyds(cost,n);

System.out.println(" Transitive closure for the given cost matrix is:");

for(i=1;i<=n;i++)

{System.out.println();

for(j=1;j<=n;j++)

System.out.print("\t"+cost[i][j]);

}

}

}

Page 54: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 54

SAMPLE INPUT AND OUTPUT:

Enter the number of vertices:

4

Enter the cost matrix

0 999 3 999

2 0 999 999

999 7 0 1

6 999 999 0

Transitive closure for the given cost matrix is:

0 10 3 4

2 0 5 6

7 7 0 1

6 16 9 0

b) Travelling Sales Person problem

ALGORITHM:

Algorithm: Traveling-Salesman-Problem

C ({1}, 1) = 0

for s = 2 to n do

for all subsets S Є {1, 2, 3, … , n} of size s and

containing 1 C (S, 1) = ∞

for all j Є S and j ≠ 1

C (S, j) = min {C (S – {j}, i) + d(i, j) for i Є S and i ≠ j}

Return minj C ({1, 2, 3, …, n}, j) + d(j, i)

Page 55: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 55

import java.util.Scanner;

public class tsp

{

public static void main(String[] args)

{

Scanner in = new Scanner(System.in);

int c[][]=new int[10][10], tour[]=new int[10];

int i, j,cost;

System.out.print("Enter No. of Cities: ");

int n = in.nextInt();

if(n==1)

System.out.println("Path is not possible");

System.exit(0);

System.out.println("Enter the Cost Matrix");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

System.out.println("\n\n\tTravelling Salesperson Problem\n");

System.out.println("\tThe Cost Matrix is\n");

for(i=1;i<=n;i++)

for(j=1;j<=n;j++)

System.out.print("\t"+c[i][j]);

System.out.println();

for(i=1;i<=n;i++)

c[i][j] = in.nextInt();

tour[i]=i;

Page 56: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 56

for(i=start+1; i<=n; i++)

cost = tspdp(c, tour, 1, n);

System.out.print("\n\n\tThe Optimal Tour is = ");

for(i=1;i<=n;i++)

System.out.print(tour[i]+"->");

System.out.println("1");

System.out.print("\n\n\tMinimum Cost = "+cost);

}

static int tspdp(int c[][], int tour[], int start, int n)

{

int mintour[]=new int[10], temp[]=new int[10], mincost=999,

ccost, i, j, k;

if(start == n-1)

{

return (c[tour[n-1]][tour[n]] + c[tour[n]][1]);

}

for(j=1; j<=n; j++)

temp[j] = tour[j];

mincost = c[tour[start]][tour[i]] + ccost;

for(k=1; k<=n; k++)

mintour[k] = temp[k];

}

for(i=1; i<=n; i++)

tour[i] = mintour[i];

return mincost;

}

temp[start+1] = tour[i];

temp[i] = tour[start+1];

if((c[tour[start]][tour[i]]+(ccost=tspdp(c,temp,start+1,n)))<mincost)

Page 57: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 57

}

}

SAMPLE INPUT AND OUTPUT:

Enter No. of Cities: 4

Enter the Cost Matrix

0 10 15 20

5 0 9 10

6 13 0 12

8 8 9 0

Travelling Salesperson Problem

The Cost Matrix is

0 10 15 20

5 0 9 10

6 13 0 12

8 8 9 0

The Optimal Tour is = 1->2->4->3->1

Minimum Cost = 35

Page 58: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 58

Exp No: 11 Subset Sum problem Date: ……………….

AIM:

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.

ALGORITHM:

initialize a list S to contain one element 0.

for each i from 1 to N do

let T be a list consisting of xi + y, for all y in S

let U be the union of T and S

sort U

make S empty

let y be the smallest element of U

add y to S

for each element z of U in increasing order do

//trim the list by eliminating numbers close to one another

//and throw out elements greater than s

if y + cs/N < z ≤ s, set y = z and add z to S

if S contains a number between (1 − c)s and s, output yes, otherwise no

PROGRAM:

import java.util.*;

public class subset {

static int d ;

static int s[]=new int [10];

static int x[]=new int [10];

//void sumofsub ( int , int , int ) ;

public static void main(String[] args) {

// TODO Auto-generated method stub

Page 59: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 59

int n , sum = 0 ;

int i ;

Scanner in = new Scanner(System.in);

System.out.println (" Enter the size of the set : " ) ;

n=in.nextInt();

System.out.println ( " \n Enter the set in increasing order:" ) ;

for ( i = 1 ; i <= n ; i++ )

s[i]=in.nextInt();

System.out.println ( " \n Enter the value of d : \n " ) ;

d=in.nextInt();

for ( i = 1 ; i <= n ; i++ )

sum = sum + s[i] ;

if ( sum < d || s[1] > d )

System.out.println ( " No subset possible : " ) ;

else

sumofsub(0,1,sum);

}

public static void sumofsub ( int m , int k , int r )

{

int i=1 ;

x[k] = 1 ;

if ( ( m + s[k] ) == d )

{

System.out.println("Subset:");

for ( i = 1 ; i <= k ; i++ )

if ( x[i] == 1 )

System.out.println( "\t" + s[i] ) ;

}

else

if ( m + s[k] + s[k+1] <= d )

sumofsub ( m + s[k] , k + 1 , r - s[k] ) ;

if ( ( m + r - s[k] >= d ) && ( m + s[k+1] <=d ) )

{

x[k] = 0;

Page 60: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 60

sumofsub ( m , k + 1 , r - s[k] ) ;

}

}

}

SAMPLE INPUT AND OUTPUT:

Enter the size of the set :

5

Enter the set in increasing order:

2 4 6 8 5

Enter the value of d :

10

Subset:

2

8

Subset:

4

6

Page 61: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 61

Exp No: 12 Hamiltonian Cycles using backtracking

principle

Date: ……………….

AIM:

Design and implement in Java to find all Hamiltonian Cycles in a connected undirected

Graph G of n vertices using backtracking principle.

PROGRAM:

import java.util.Scanner;

public class hamiltonian

{

static int x[] = new int[10];

public static void main(String[] args)

{

Scanner sc = new Scanner(System.in);

int i,j,x1, x2, edges, n;

int g[][] = new int[10][10];

System.out.print("Enter No. of Vertices: ");

n = sc.nextInt();

for(i=1;i<=n;i++)

{

for(j=1;j<=n;j++)

g[i][j] = 0;

x[i]=0;

}

System.out.print("Enter No. of Edges: ");

edges = sc.nextInt();

for(i=1;i<=edges;i++)

{

System.out.println("Enter the Edge"+i+": ");

{

}

Page 62: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 62

x1 = sc.nextInt();

x2 = sc.nextInt();

g[x1][x2] = 1;

g[x2][x1] = 1;

}

x[1] = 1;

System.out.println("\n\nHamiltonian Cycle\n");

hcycle(g,n,2);

}

public static void nextvalue(int g[][],int n,int k)

{

int j;

while(true)

{

x[k] = (x[k] + 1) % (n+1);

if(x[k] == 0)

return;

if(g[x[k-1]][x[k]] == 1)

{

for(j=1;j<=k-1;j++)

}

public static void hcycle(int g[][],int n, int k)

{

int i;

while(true)

{

{ if(x[j] == x[k] )

break;

}

if(j == k)

{ if((k<n) || ((k==n) && (g[x[n]][x[1]] == 1)))

return;

}

}

}

Page 63: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 63

nextvalue(g,n,k);

if(x[k]== 0)

return;

if(k==n)

for(i=1;i<=n;i++)

System.out.print(x[i]+"-->");

System.out.println(x[1]+"\n");

else

hcycle(g,n,k+1);

}

}

}

SAMPLE INPUT AND OUTPUT:

Enter No. of Vertices: 6

Enter No. of Edges: 10

Enter the Edge1:

1 2

Enter the Edge2:

1 3

Enter the Edge3:

1 6

Enter the Edge4:

2 4

Enter the Edge5:

2 6

Enter the Edge6:

3 4

{

}

Page 64: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 64

Enter the Edge7:

3 5

Enter the Edge8:

3 6

Enter the Edge9:

4 5

Enter the Edge10:

4 6

Hamiltonian Cycle

1-->2-->4-->5-->3-->6-->1

1-->2-->6-->4-->5-->3-->1

1-->3-->5-->4-->2-->6-->1

1-->3-->5-->4-->6-->2-->1

1-->6-->2-->4-->5-->3-->1

Page 65: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 65

MULTIPLE CHOICE QUESTIONS

1. You have to sort a list L consistnn of a sorted list followed by a few

random el- ements. Which of the followinn sortnn methods would be

especially suitable for such a task?

A) Bubble sort

B) Selecton sort

C) Quick sort

D) Inserton sort

2. A technique for direct search is .......................................

A) Binary Search

B) Linear Search

C) Tree Search D) Hashinn

3. The searchinn technique that takes O(1) tme to fnd a data is

(A) Linear Search

(B) Binary Search

(C) Hashinn (D) Tree Search

4. The number of interchannes required to sort 5, 1, 6, 2 4 in ascendinn order

usinn Bubble Sort is

(A) 6

(B) 5

(C) 7

(D) 8

5. The postix form of the expression (A + B) ∗ (C ∗ D − E) ∗ F/G is

(A) AB + CD ∗ E − FG/ ∗ ∗

(B) AB + CD ∗ E − F ∗ ∗G/

(C) AB + CD ∗ E − ∗F ∗ G/

(D) AB + CDE ∗ − ∗ F ∗ G/

6. The complexity of multplyinn two matrices of order m*n and n*p is

(A) mnp

(B) mp

(C) mn

Page 66: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 66

(D) np

7. In worst case Quick Sort has order

(A) O (n lon n)

(B) O (lon n)

(C) O (n 2 /2)

(D) O (n 2 /4)

8. A full binary tree with 2n+1 nodes contain

(A) n leaf nodes (B) n non-leaf nodes (C) n-1 leaf nodes (D) n-1 non-leaf nodes

9. A linear list of elements in which deleton can be done from one end

(front) and inserton can take place only at the other end (rear) is known as

a

(A) queue.

(B) stack.

(C) tree.

(D) linked list.

10. A sort which relatvely passes throunh a list to exchanne the frst element

with any element less than it and then repeats with a new frst element is

called

(A) inserton sort.

(B) selecton sort.

(C) heap sort.

(D) quick sort.

Page 67: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 67

11. Which of the followinn sortnn alnorithms does not have a worst case

runninn tme of O(n 2 ) ?

(A) Inserton sort

(B) Merne sort

(C) Quick sort

(D) Bubble sort

12. Consider a linked list of n elements. What is the tme taken to insert an

element after an element pointed by some pointer?

(A) O (1)

(B) O ( lon 2 n )

(C) O (n)

(D) O ( n lon 2 n )

13. The data structure required for Breadth First Traversal on a nraph is

(A) queue

(B) stack

(C) array

(D) tree

14. In a circular linked list

(A) components are all linked tonether in some sequental manner.

(B) there is no beninninn and no end.

(C) components are arranned hierarchically.

(D) forward and backward traversal within the list is permited.

15. The quick sort alnorithm exploit ————– desinn technique

(A) Greedy

(B) Dynamic pronramminn

(C) Divide and Conquer

(D) Backtrackinn

16. The number of diferent directed trees with 3 nodes are

(A) 2

(B) 3

(C) 4

(D) 5

17. The data structure required to evaluate a postix expression is

Page 68: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 68

(A) queue

(B) stack

(C) array

(D) linked-list

18. The data structure required to check whether an expression contains

balanced parenthesis is

(A) Stack

(B) Queue

(C) Tree

(D) Array

19. The complexity of searchinn an element from a set of n elements usinn Binary

search alnorithm is

(A) O(n)

(B) O(lon n)

(C) O(n 2 )

(D) O(n lon n)

20. What data structure would you mostly likely see in a nonrecursive

implementaton of a recursive alnorithm?

(A) Stack

(B) Linked list

(C) Queue

(D) Trees

Page 69: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 69

Which of the followinn sortnn methods would be most suitable for

sortnn a list which is almost sorted ?

(A) Bubble Sort

(B) Inserton Sort

(C) Selecton Sort

(D) Quick Sort

22. A binary tree of depth ”d” is an almost complete binary tree if

(A) Each leaf in the tree is either at level ”d” or at level ”d-1”

(B) For any node ”n” in the tree with a rinht descendent at level ”d”

all the left descendent of ”n” that are leaves, are also at level ”d”

(C) Both (A) & (B)

(D) None of the above

23. If the address of A[1][1] and A[2][1] are 1000 and 1010 respectvely and

each ele- ment occupies 2 bytes then the array has been stored in ————

— order.

(A) row major

(B) column major

(C) matrix major

(D) none of these

24. An adjacency matrix representaton of a nraph cannot contain informaton of :

(A) nodes

(B) ednes

(C) directon of ednes

(D) parallel ednes

25. O(N) (linear tme) is beter than O(1) constant tme.

(A) True

(B) False

26. The best averane behaviour is shown by

(A) Quick Sort

(B) Merne Sort

(C) Inserton Sort

(D) Heap Sort

27. A queue is a,

(A) FIFO (First In First Out) list.

Page 70: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 70

(C) Ordered array.

(B) LIFO (Last In First Out) list.

(D) Linear tree.

28. Which data structure is needed to convert infx notaton to postix notaton?

(A) Branch

(B) Queue

(C) Tree

(D) Stack

29. Consider that n elements are to be sorted. What is the worst case tme

complexity of Bubble sort?

(A) O(1)

(C) O(n)

(B) O(lon 2 n)

(D) O(n 2 )

30. A characteristc of the data that binary search uses but the linear search

innores is the ——————-.

(A) Order of the elements of the list.

(B) Lennth of the list.

(C) Maximum value in list.

(D) Type of elements of the list.

31. In Breadth First Search of Graph, which of the followinn data structure is used?

(A) Stack.

(B) Queue.

(C) Linked List.

Page 71: Lab manual Design & analysis of algorithms laboratory 18CSl47...Design & Analysis of Algorithm [18CSL47] Dept of I S E Page 3 5. Sort a given set of n integer elements using Merge

Design & Analysis of Algorithm [18CSL47]

Dept of I S E Page 71

(D) None of the above.

32. In order to net the contents of a Binary search tree in ascendinn order, one

has to traverse it in

(A) pre-order.

(B) in-order.

(C) post order.

(D) not possible.

33. In binary search, averane number of comparison required for searchinn an

element in a list if n numbers is

(A) lon 2 n .

(B) n / 2 .

(C) n.

(D) n - 1.

34. The worst case of quick sort has order

(A) O(n 2 )

(B) O(n)

(C) O (n lon 2 n)

(D) O (lon 2 n)

35. The tme required to delete a node x from a doubly linked list havinn n nodes is

(A) O (n)

(B) O (lon n)

(C) O (1)

(D) O (n lon n)