You are on page 1of 36

GOVERNMENT ENGINEERING COLLEGE - RAJKOT

CERTIFICATE

This is to certify that

Mr. Harshil Kaneria

Enrolment No: 190200107058


Branch: Computer Engineering
5th
Semester: Division: E Batch: E2

has satisfactorily completed the term work in the subject Analysis and
Design of Algorithms (3150703)

Date of Submission:21/09/2021

Subject-In charge Head of the Department


Enrollment No. 190200107058 Name – Harshil Kaneria

INDEX

Page
List of Practical Date Sign
No.
1: Implement and Analyze
Find factorial number of given integer using 3 08/06/21
1.1
iterative and recursive method.
4 22/06/21
1.2 Linear Search algorithm.
Selection Sort, Bubble Sort and Insertion Sort 5 06/07/21
1.3
algorithms.
1.4 Max heap Sort algorithm. 9 27/07/21

2: Implement and Analyze: Divide and Conquer


2.1 Binary Search 11 27/07/21

2.2 Quick Sort 14 13/07/21

2.3 Merge Sort 15 20/07/21

3: Implement: Greedy algorithms


3.1 Fractional Knapsack Problem 18 03/08/21

3.2 Activity Selection 19 03/08/21

3.3 Job Scheduling 21 10/08/21

3.4 Prim’s Algorithm 23 10/08/21

3.5 Krushkal’s Algorithm 25 17/08/21

4: Implement: Dynamic Programming


4.1 Making Change Problem 28 24/08/21

4.2 0/1 Knapsack Problem 29 31/08/21

4.3 Longest Common Subsequence 30 31/08/21

4.4 Chained Matrix Multiplication 32 07/09/21

5: Implement : Graphs
5.1 Breadth First Search 33 07/09/21

5.2 Depth First Search 34 21/09/21

2
Enrollment No. 190200107058 Name – Harshil Kaneria

1.1 Find factorial number of given integer using iterative and recursive method.

Recursive method:
import java.util.*;
public class Factorial{
public static void main(String args[]){
System.out.print("Enter A Number:");
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
System.out.println("Factorial of "+n+ " is: "+fact(n));
}
public static int fact(int n){
if(n==1){
return 1;
}
return n*fact(n-1);
}
}
Output:
Enter A Number:7
Factorial of 7 is: 5040

Iterative method:
import java.util.*;
public class Factorial2 {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter a Number:");
int n=sc.nextInt();
int fact=1;
for(int i=n;i>1;i--){
fact*=i;
}
System.out.println("Factorial of "+n+" is: "+fact);
}
}

Output:
Enter a Number:
6
Factorial of 6 is: 720

3
Enrollment No. 190200107058 Name – Harshil Kaneria

1.2 Linear Search algorithm.

import java.util.*;
public class linearsearch{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
Random rd= new Random();
System.out.println("Enter number of element which you want to enter:");
int n=sc.nextInt();
int[] a= new int[n];
a[0]=5;
for(int i=1;i<n;i++){
a[i]=rd.nextInt();
}
System.out.println("Enter number which you want to search:");
int m=sc.nextInt();
int i=0;
long start= System.nanoTime();
for(i=0;i<n;i++){
if(a[i]==m){
break;
}
}
long end = System.nanoTime();
long runningTime= (end-start)/1000;
if(i==n){
System.out.println(m+" is not found & running time of algorithm is:"+
runningTime+" microseconds.");
}
else{
System.out.println("index of "+m+" is: "+(i+1)+" & running time of algorithm is:
" +runningTime+" microseconds.");
}
}
}

Output:

Enter number of element which you want to enter:


6
Enter number which you want to search:
43 23 12 45 23 111
43 is not found & running time of algorithm is:0 microseconds.

4
Enrollment No. 190200107058 Name – Harshil Kaneria

Linear Search Output


Select key →best case → first element of array
Select key →worst case → key not found in array

No. of elements (N) Best Case Running Worst Case Running


Time (microseconds) Time (microseconds)
1000 1 41
2000 1 76

3000 1 115
4000 1 141
5000 1 231
6000 1 193
7000 1 309
8000 1 315

9000 1 372
10000 1 466

1.3 Selection Sort, Bubble Sort and Insertion Sort algorithms.

Selection Sort:

import java.util.*;
public class selectionsort {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
Random rd = new Random();
System.out.println("Enter number of element:");
int n=sc.nextInt();
// System.out.println("Enter numbers:");
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=rd.nextInt();
}
int comp= 0,sw=0;
System.out.println("After Sorting:");
long start = System.nanoTime();
for(int i=0;i<n;i++){
int min=i;
for(int j=i+1;j<n;j++){
if(a[min]>a[j]){
++comp;

5
Enrollment No. 190200107058 Name – Harshil Kaneria

min=j;
}
}
++sw;
int temp= a[min];
a[min]=a[i];
a[i]=temp;
}
long end = System.nanoTime();
long runningTime = (end - start)/1000;
/*for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}*/
System.out.println("Running time of this algorithm is: "+runningTime+" microseconds
& Swaps: "+sw+" , comparition: "+comp );
}
}

Output:

Enter number of element:


10
After Sorting:
Running time of this algorithm is: 3 microseconds & Swaps: 10 , comparition: 14

Bubble Sort:

import java.util.*;
public class bubblesort {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter number of element:");
int n=sc.nextInt();
System.out.println("Enter numbers:");
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
System.out.println("After Sorting:");
int temp=0;
for(int i=0;i<n;i++){
for(int j=0;j<n-1;j++){
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}

6
Enrollment No. 190200107058 Name – Harshil Kaneria

for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
}
}

Output:

Enter number of element:


10
Enter numbers:
34 23 212 45 34 239 68 48 23 56
After Sorting:
23 23 34 34 45 48 56 68 212 239

Insertion Sort:

import java.util.*;
public class insertionsort{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
Random rd= new Random();
System.out.println("Enter Number of interger:");
int n=sc.nextInt();
System.out.println("Enter "+n+" numbers");
int[] a= new int[n];
for(int i=0;i<n;i++){
a[i]=n-i;
}
long start= System.nanoTime();
int temp=0,cmp=0,swp=0;
for(int i=0;i<n;i++){
temp=a[i];
int j=0;
for(j=i-1;j>=0 && temp<a[j];j--){
++cmp;
++swp;
a[j+1]=a[j];
}
a[j+1]=temp;
}
long end = System.nanoTime();
long timetkn = (end-start)/1000;
System.out.println("Your array after Sorting:");
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
System.out.println("Time : "+timetkn+" ms\ncamparision: "+(cmp)+"\nswap: "+swp);
}
}

7
Enrollment No. 190200107058 Name – Harshil Kaneria

Output:

Enter Number of interger:


10
Enter 10 numbers
Your array after Sorting:
1 2 3 4 5 6 7 8 9 10 Time : 3 ms
camparision: 45
swap: 45

Best case Selection Bubble Insertion

Running Time

Running Time

Running Time
(microsecond

(microsecond

(microsecond
elements (N)

comparisons

comparisons

comparisons
swapping

swapping

swapping
No. of

No. of

No. of

No. of

No. of

No. of

No. of
s)

s)

s)
1000 5525 1000 3981 999 0 7 1000 0 43
2000 12268 2000 7630 1999 0 11 2000 0 92
3000 19869 3000 11278 2999 0 17 3000 0 169
4000 27539 4000 14065 3999 0 29 4000 0 201
5000 34870 5000 18087 4999 0 35 5000 0 203
6000 44644 6000 24003 5999 0 55 6000 0 287
7000 52917 7000 30130 6999 0 53 7000 0 639

8000 60247 8000 38087 7999 0 58 8000 0 688


9000 69847 9000 81408 8999 0 60 9000 0 776
10000 79290 10000 58356 9999 0 72 10000 0 811

Worst Selection Bubble Insertion


Case
Running Time

Running Time

Running Time
(microsecond

(microsecond

(microsecond
elements (N)

comparisons

comparisons

comparisons
swapping

swapping

swapping
No. of

No. of

No. of

No. of

No. of

No. of

No. of
s)

s)

s)

1000 499500 500 3107 499500 499500 9540 499500 499500 1615
3
2000 1999000 1000 11848 1999000 1999000 22907 1999000 1999000 2399
1
3000 4498500 1500 25777 4498500 4498500 49982 4498500 4498500 2799

8
Enrollment No. 190200107058 Name – Harshil Kaneria

4000 7998000 2000 45196 7998000 7998000 115526 7998000 7998000 2802
3
5000 12497500 2500 63606 1249750 1249750 188015 1249750 1249750 2325
0 0 0 0 8
6000 17997000 3000 83875 1799700 1799700 225770 1799700 1799700 3422
0 0 0 0 4
7000 24496500 3500 105277 2449650 2449650 334299 2449650 2446500 4465
0 0 0 9
8000 31996000 4000 137114 3199600 31996000 356100 3199600 3199600 4180
0 0 0 3
9000 40495500 4500 158091 4049550 4049550 439208 4049550 4049550 4980
0 0 0 0 5
10000 49995000 5000 191504 4999500 4999500 567988 4999500 4999500 5281
0 0 0 0 5

1.4 Max heap Sort algorithm.


import java.util.*;
public class heapsort{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
Random rd = new Random();
System.out.println("Enter number of element:");
int n = sc.nextInt();
//System.out.println("Enter "+n+" Elements:");
int[] arr= new int[n];
for(int i=0;i<n;i++){
arr[i]=rd.nextInt();
}
long start = System.nanoTime();
sort(arr);
long end = System.nanoTime();
long runningTime = (end - start)/1000;
System.out.println("Sorted array is");
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println("Runnign Time of algorithm is: "+runningTime+" microseconds");
}
public static void sort(int arr[])
{
int n = arr.length;
for (int i = n / 2 - 1; i >= 0; i--){
heapify(arr, n, i);

9
Enrollment No. 190200107058 Name – Harshil Kaneria

}
for (int i = n - 1; i > 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
public static void heapify(int arr[], int n, int i)
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest]){
largest = l;
}
if (r < n && arr[r] > arr[largest]){
largest = r;
}
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
}

Output:

Enter number of element:


10
Sorted array is
-2067052708 -2064542812 -1357692425 -1272094174 -1261107736 -283147235 144441598
828833725 1238094412 1736829959 Runnign Time of algorithm is: 7 microseconds

10
Enrollment No. 190200107058 Name – Harshil Kaneria

(microseconds)
No. of elements

Running Time
(N)

10 17
15 21
20 12
25 31
30 43

2.1 Binary Search

import java.util.*;
public class binarysearch {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
Random rd = new Random();
System.out.println("Enter number of elements:");
int n =sc.nextInt();
System.out.println("Enter number which you want to find:");
int m= sc.nextInt();
int[] a= new int[n];
for(int i=0;i<n;i++){
a[i]=rd.nextInt(10000-6)+6;
//System.out.println(a[i]+" ");
}
Arrays.sort(a);
long start= System.nanoTime();
int l = 0,r=n-1,mid = (l+r)/2;
//a[mid]=m;
while(l<=r){

11
Enrollment No. 190200107058 Name – Harshil Kaneria

//System.out.print(mid+" ");
if(a[mid]==m){
System.out.println(m+" is present at: "+ (mid+1));
break;
}
else if(a[mid]>m){
r=mid-1;
}
else{
l = mid+1;
}
mid = (r+l)/2;
}
long end = System.nanoTime();
if(l>r){
System.out.println(m+ " is not found.");
}
long totaltime= (end-start)/1000;
System.out.println("Total time taken to execute this program is:"+totaltime+" ms");
}
}

Output:

Enter number of elements:


5
Enter number which you want to find:
34
34 is not found.
Total time taken to execute this program is:0 ms

Binary Search Output

Take Sorted array as input.


In best case, consider middle element of array for search.
In worst case, consider first element of array for search.

12
Enrollment No. 190200107058 Name – Harshil Kaneria

No. of elements (N) Best Case Running Worst Case Running


Time (microseconds) Time
(microseconds)
1000 1 8189
2000 1 10425
3000 1 10044
4000 1 10675
5000 1 11183
6000 1 13565
7000 1 11382
8000 1 11129
9000 1 10709
10000 1 10369

13
Enrollment No. 190200107058 Name – Harshil Kaneria

2.2 Quick Sort

import java.util.*;
public class quicksort {
static int par=0;
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
Random rd= new Random();
System.out.println("Enter Number of Elements:");
int n = sc.nextInt();
int[] a= new int[n];
for(int i=0;i<n;i++){
a[i] = sc.nextInt();
}
int C=0;
long start= System.nanoTime();
qksort(a,0,n-1);
long end = System.nanoTime();
long timetkn=(end-start)/1000;
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
System.out.println("Time: "+timetkn+" ms & partition: "+par+ " "+C);
}
public static void qksort(int[] a,int l, int r){
if(l<r){
int p = partition(a,l,r);
qksort(a, l, p-1);
qksort(a, p+1, r);
}
}
public static int partition(int[] a, int l, int r){
int p = a[r],i=l-1,temp=0;
for(int j=l;j<r;j++){
if(p>a[j]){
++i;
++C;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp = a[i+1];
a[i+1] = a[r];

14
Enrollment No. 190200107058 Name – Harshil Kaneria

a[r] = temp;
return (i+1);
}
}

Output:

Enter Number of Elements:


10
12 34 32 68 34 283 45 238 546 1
1 12 32 34 34 45 68 238 283 546 Time: 9 ms & partition: 6

2.3 Merge Sort

import java.util.*;
public class mergesort1 {
static int mg=0;
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
Random rd= new Random();
System.out.println("Enter number of element:");
int n = sc.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++){
a[i] = rd.nextInt(100 - 1)+1;
}
long start = System.nanoTime();
int p=0,r=n-1;
if(p<r){
int q = (p+r)/2;
mergesort(a,p,q);
mergesort(a,q+1,r);
merge(a,p,q,r);
}
long end = System.nanoTime();
long time = (end-start)/1000;
System.out.println("Array after sorting:");
for(int i=0;i<n;i++){
System.out.print(a[i]+" ");
}
System.out.println("\nTime for execution: "+time+" ms & Total Merge Call: "+ mg);

}
public static void mergesort(int[] a,int p, int r){

15
Enrollment No. 190200107058 Name – Harshil Kaneria

int q=(p+r)/2;
if(p>=r){
return;
}
mergesort(a, p, q);
mergesort(a,q+1,r);
merge(a,p,q,r);
}
public static void merge(int[] a,int p, int q, int r){
mg+=1;
int n1 = q+1-p;
int n2 = r-q;
int[] l = new int[n1];
int [] m = new int[n2];
int i,j=0;
for(i=0;i<n1;i++){
l[i]=a[p+i];
}
for(j=0;j<n2;j++){
m[j]=a[q+1+j];
}
i=0;j=0;
while(i<n1 && j<n2)
{
if(l[i]<=m[j])
{
a[p]=l[i];
p++;
i++;
}
else
{
a[p]=m[j];
p++;
j++;
}
}
while(i<n1)
{
a[p]=l[i];
i++;
p++;
}
while(j<n2)

16
Enrollment No. 190200107058 Name – Harshil Kaneria

{
a[p]=m[j];
j++;
p++;
}
}
}

Output:

Enter number of element:


10
Array after sorting:
17 35 37 37 46 52 60 60 68 91
Time for execution: 22 ms & Total Merge Call: 9

Take all the input elements in sorted order.


In quick sort – best case, select middle element of array as pivot
In quick sort – worst case, select first element of array as pivot

Merge Sort Quick Sort


Best Case Worst Case
(microseconds)

(microseconds)

(microseconds)
No. of elements

No. of Partition

No. of Partition
Running Time

Running Time

Running Time
No. of Merge
Calls

Calls

Calls
(N)

10 9 20 6 4 9 7
15 14 26 9 8 14 8
20 19 39 15 10 19 9
25 24 37 18 14 24 15
30 29 59 21 18 29 28

17
Enrollment No. 190200107058 Name – Harshil Kaneria

3.1 Fractional Knapsack Problem

import java.util.*;
public class greedyknapsack{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
Random rd = new Random();
System.out.println("Enter number of pairs");
int n = sc.nextInt();
System.out.println("Enter value and weights of each item:");
int[] v= new int[n];
int[] w= new int[n];
float[] r= new float[n];
for(int i=0;i<n;i++){
v[i]=sc.nextInt();
w[i]=sc.nextInt();
r[i]=(float)v[i]/w[i];
}
/*for(int i=0;i<n;i++){
System.out.print(r[i]+" ");
}*/
System.out.println("Enter total weight of bag:");
int weight=sc.nextInt();
int max=0,value=0;
long start= System.nanoTime();
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(r[j]>r[max]){
max= j;
}
}
if(weight>0){
if(weight/w[max]<1){
value += (v[max]*weight)/w[max];
w[max] -= (w[max]-weight);
weight=0;
}
else{
value += v[max];
weight-=w[max];
}
}
else{

18
Enrollment No. 190200107058 Name – Harshil Kaneria

break;
}
r[max]=0;
max=0;
}
long end = System.nanoTime();
long runningtime = (end - start)/1000;
System.out.println("Maximum value of Knapsack Is: "+value+" & running time is:
"+runningtime+" microseconds");
}
}

Output:

Enter number of pairs


4
Enter value and weights of each item:
10 3
12 4
15 6
20 5
Enter total weight of bag:
10
Maximum value of Knapsack Is: 36 & running time is: 2 microseconds

3.2 Activity Selection

import java.util.*;
public class greedyactivityselection {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter Number of activity you want to perform: ");
int n = sc.nextInt();
int[] start = new int[n];
int[] end = new int[n];
System.out.println("Enter starting and ending time of each job:");
for(int i=0;i<n;i++){
start[i]=sc.nextInt();
end[i]=sc.nextInt();
}
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(end[j]<end[i]){

19
Enrollment No. 190200107058 Name – Harshil Kaneria

int temp = end[j];


end[j] = end[i];
end[i] = temp;
temp = start[j];
start[j] = start[i];
start[i] = temp;
}
else if(end[j]==end[i]&& start[j]<start[i]){
int temp = end[j];
end[j] = end[i];
end[i] = temp;
temp = start[j];
start[j] = start[i];
start[i] = temp;
}
}
}
int[] selected = new int[n];
selected[0]=1;
int j=0,p=1;
for(int i=1;i<n;i++){
if(start[i]>=end[j]){
selected[p]=i+1;
++p;
j=i;
}
}
System.out.println("Selected activities are:");
for(int i=0;selected[i]!=0;i++){
System.out.print(selected[i]+" ");
}
}
}

Output:

Enter Number of activity you want to perform:


4
Enter starting and ending time of each job:
25
13
57
36

20
Enrollment No. 190200107058 Name – Harshil Kaneria

Selected activities are:


13

3.3 Job Scheduling

import java.util.*;
public class greedyjobscheduling {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter Number of job: ");
int n =sc.nextInt();
System.out.println("Enter choice:\n Profit - 0\n loss - 1 ");
int choice = sc.nextInt();
int[][] job = new int[n][3];
//first=profit, second = deadline, third = name
System.out.println("Enter Profite/Penalty and deadline for each Job:");
for(int i=0;i<n;i++){
job[i][0]=sc.nextInt();
job[i][1]=sc.nextInt();
job[i][2]=i+1;
}
sortbyColumn(job, 0);
/* for(int i=0;i<n;i++){
System.out.print(job[i][0]+" "+job[i][1]+" "+job[i][2]+"\n");
}*/
int[][] selected = new int[n][3];
int profit = 0;
//first = date, second = time, third = name
for(int i=0;i<n;i++){
selected[i][0]=i+1;
selected[i][1]=0;
selected[i][2]=0;
}
if(choice == 0){
for(int i=0;i<n/2;i++){
for(int j=0;j<3;j++){
int temp = job[i][j];
job[i][j]=job[n-i-1][j];
job[n-i-1][j]=temp;
}
}
for(int i=0;i<n;i++){
for(int j=job[i][1];j>0;j--){

21
Enrollment No. 190200107058 Name – Harshil Kaneria

if(selected[j][1]==0){
selected[j][1] = 1;
selected[j][2]=job[i][2];
profit+= job[i][0];
break;
}
}
}
System.out.println("Your maximum profit by this job scheduling is: "+profit);
}
else{
for(int i=0;i<n;i++){
for(int j=job[i][1];j>0;j--){
if(selected[j][1]==0){
selected[j][1] = 1;
selected[j][2]=job[i][2];
profit+= job[i][0];
break;
}
}
}
System.out.println("Your minimum penalty by this job scheduling is: "+profit);
}
/* for(int i=0;i<n;i++){
System.out.print(selected[i][0]+" "+selected[i][1]+" "+selected[i][2]+"\n");
}*/
}
public static void sortbyColumn(int arr[][], int col){
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1, final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
}

22
Enrollment No. 190200107058 Name – Harshil Kaneria

Output:

Enter Number of job:


5
Enter choice:
Profit - 0
loss - 1
0
Enter Profite/Penalty and deadline for each Job:
13
24
32
41
52
Your maximum profit by this job scheduling is: 12

3.4 Prim’s Algorthim:

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

class primsalgo {
private static final int V = 5;
int minKey(int key[], Boolean mstSet[])
{
int min = Integer.MAX_VALUE, min_index = -1;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}

return min_index;
}
void printMST(int parent[], int graph[][])
{
System.out.println("Edge \tWeight");
for (int i = 1; i < V; i++)
System.out.println(parent[i] + " - " + i + "\t" +
graph[i][parent[i]]);
}

23
Enrollment No. 190200107058 Name – Harshil Kaneria

void primMST(int graph[][])


{
int parent[] = new int[V];
int key[] = new int[V];
Boolean mstSet[] = new Boolean[V];
for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++){
if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v]
< key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
printMST(parent, graph);
}
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter number of nodes:");
int n = sc.nextInt();
int[][] a= new int[n+1][n+1];
System.out.println("Enter path values in following manner:");
System.out.print("a b c . . .\nb 1 2\nc 2 3\n.\n.\n.\n");
for(int i=0;i<n+1;i++){
a[0][i]=(i+1);
a[i][0]=(i+1);
}
for(int i=1;i<n+1;i++){
for(int j=1;j<n+1;j++){
a[i][j]=sc.nextInt();
}
}
primMST(a);
}

24
Enrollment No. 190200107058 Name – Harshil Kaneria

Output:

Enter number of nodes:


4
Enter path values in following manner:
abc...
b12
c23
.
.
.
1254
2430
4210
0031
Edge Weight
0-1 2
1-2 2
2-3 2
1-4 0

3.5 Krushkal’s Algorithm

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

class kruskalsalgo {
class Edge implements Comparable<Edge>
{
int src, dest, weight;
public int compareTo(Edge compareEdge)
{
return this.weight - compareEdge.weight;
}
};
class subset
{
int parent, rank;
};
int V, E;

25
Enrollment No. 190200107058 Name – Harshil Kaneria

Edge edge[];
kruskalsalgo(int v, int e)
{
V = v;
E = e;
edge = new Edge[E];
for (int i = 0; i < e; ++i)
edge[i] = new Edge();
}
int find(subset subsets[], int i)
{
if (subsets[i].parent != i)
subsets[i].parent
= find(subsets, subsets[i].parent);

return subsets[i].parent;
}
void Union(subset subsets[], int x, int y)
{
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank
< subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank
> subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
void KruskalMST()
{
Edge result[] = new Edge[V];
int e = 0;
int i = 0;
for (i = 0; i < V; ++i)
result[i] = new Edge();
Arrays.sort(edge);
subset subsets[] = new subset[V];
for (i = 0; i < V; ++i)
subsets[i] = new subset();

26
Enrollment No. 190200107058 Name – Harshil Kaneria

for (int v = 0; v < V; ++v)


{
subsets[v].parent = v;
subsets[v].rank = 0;
}

i = 0;
while (e < V - 1)
{
Edge next_edge = edge[i++];

int x = find(subsets, next_edge.src);


int y = find(subsets, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
}
System.out.println("Following are the edges in "
+ "the constructed MST");
int minimumCost = 0;
for (i = 0; i < e; ++i)
{
System.out.println(result[i].src + " -- "
+ result[i].dest
+ " == " + result[i].weight);
minimumCost += result[i].weight;
}
System.out.println("Minimum Cost Spanning Tree "
+ minimumCost);
}
public static void main(String[] args)
{
int V = 4;
int E = 5;
kruskalsalgo graph = new kruskalsalgo(V, E);
graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = 10;
graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 6;
graph.edge[2].src = 0;

27
Enrollment No. 190200107058 Name – Harshil Kaneria

graph.edge[2].dest = 3;
graph.edge[2].weight = 5;
graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 15;
graph.edge[4].src = 2;
graph.edge[4].dest = 3;
graph.edge[4].weight = 4;
graph.KruskalMST();
}
}

Output:

Following are the edges in the constructed MST


2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Cost Spanning Tree 19

4.1 Making Change Problem

import java.io.*;

class makingchangedp
{
static int minCoins(int coins[], int m, int V)
{
int table[] = new int[V + 1];

table[0] = 0;
for (int i = 1; i <= V; i++)
table[i] = Integer.MAX_VALUE;

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


{
for (int j = 0; j < m; j++)
if (coins[j] <= i)
{
int sub_res = table[i - coins[j]];
if (sub_res != Integer.MAX_VALUE
&& sub_res + 1 < table[i])
table[i] = sub_res + 1;

28
Enrollment No. 190200107058 Name – Harshil Kaneria

if(table[V]==Integer.MAX_VALUE)
return -1;

return table[V];

}
public static void main (String[] args)
{
int coins[] = {9, 6, 5, 1};
int m = coins.length;
int V = 11;
System.out.println ( "Minimum coins required is "+ minCoins(coins, m,
V));
}
}

Output:

Minimum coins required is 2

4.2 0/1 Knapsack Problem

class 01knapsackdp{

static int max(int a, int b)


{
return (a > b) ? a : b;
}
static int knapSackRec(int W, int wt[],int val[], int n,int [][]dp)
{

if (n == 0 || W == 0)
return 0;

if (dp[n][W] != -1)
return dp[n][W];

29
Enrollment No. 190200107058 Name – Harshil Kaneria

if (wt[n - 1] > W)

return dp[n][W] = knapSackRec(W, wt, val,n - 1, dp);

else
return dp[n][W] = max((val[n - 1] +knapSackRec(W - wt[n - 1], wt,val, n - 1,
dp)),knapSackRec(W, wt, val,n - 1, dp));
}

static int knapSack(int W, int wt[], int val[], int N)


{
int dp[][] = new int[N + 1][W + 1];
for(int i = 0; i < N + 1; i++)
for(int j = 0; j < W + 1; j++)
dp[i][j] = -1;

return knapSackRec(W, wt, val, N, dp);


}
public static void main(String [] args)
{
int val[] = { 60, 100, 120 };
int wt[] = { 10, 20, 30 };

int W = 50;
int N = val.length;

System.out.println(knapSack(W, wt, val, N));


}
}

Output:

220

4.3 Longest Common Subsequence

public class longestcommonsubsequence


{

int lcs( char[] X, char[] Y, int m, int n )


{
int L[][] = new int[m+1][n+1];

30
Enrollment No. 190200107058 Name – Harshil Kaneria

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


{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
return L[m][n];
}

int max(int a, int b)


{
return (a > b)? a : b;
}

public static void main(String[] args)


{
longestcommonsubsequence lcs = new longestcommonsubsequence();
String s1 = "AGGTAB";
String s2 = "GXTXAYB";

char[] X=s1.toCharArray();
char[] Y=s2.toCharArray();
int m = X.length;
int n = Y.length;

System.out.println("Length of LCS is" + " " +lcs.lcs( X, Y, m, n ) );


}

Output:

Length of LCS is 4

31
Enrollment No. 190200107058 Name – Harshil Kaneria

4.4 Chained Matrix Multiplication

import java.io.*;
import java.util.*;
class chainedmatrixmultiplication
{

static int[][] dp = new int[100][100];


static int matrixChainMemoised(int[] p, int i, int j)
{
if (i == j)
{
return 0;
}
if (dp[i][j] != -1)
{
return dp[i][j];
}
dp[i][j] = Integer.MAX_VALUE;
for (int k = i; k < j; k++)
{
dp[i][j] = Math.min(
dp[i][j], matrixChainMemoised(p, i, k)
+ matrixChainMemoised(p, k + 1, j)
+ p[i - 1] * p[k] * p[j]);
}
return dp[i][j];
}

static int MatrixChainOrder(int[] p, int n)


{
int i = 1, j = n - 1;
return matrixChainMemoised(p, i, j);
}
public static void main (String[] args)
{

int arr[] = { 1, 2, 3, 4 };
int n= arr.length;

for (int[] row : dp)


Arrays.fill(row, -1);

32
Enrollment No. 190200107058 Name – Harshil Kaneria

System.out.println("Minimum number of multiplications is " +


MatrixChainOrder(arr, n));
}
}

Output:

Minimum number of multiplications is 18

5.1 Breadth First Search

import java.io.*;
import java.util.*;
class bfs
{
private int V;
private LinkedList<Integer> adj[];
bfs(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
void addEdge(int v,int w)
{
adj[v].add(w);
}

void BFS(int s)
{
boolean visited[] = new boolean[V];

LinkedList<Integer> queue = new LinkedList<Integer>();

visited[s]=true;
queue.add(s);

while (queue.size() != 0)
{
s = queue.poll();
System.out.print(s+" ");

33
Enrollment No. 190200107058 Name – Harshil Kaneria

Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
public static void main(String args[])
{
bfs g = new bfs(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

System.out.println("Following is Breadth First Traversal "+


"(starting from vertex 2)");

g.BFS(2);
}
}

Output:

Following is Breadth First Traversal (starting from vertex 2)


2 031

5.2 depth First Search

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

class dfs {
private int V;

34
Enrollment No. 190200107058 Name – Harshil Kaneria

private LinkedList<Integer> adj[];

@SuppressWarnings("unchecked") dfs(int v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}

void addEdge(int v, int w)


{
adj[v].add(w);
}

void DFSUtil(int v, boolean visited[])


{
visited[v] = true;
System.out.print(v + " ");
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}

void DFS(int v)
{
boolean visited[] = new boolean[V];

DFSUtil(v, visited);
}
public static void main(String args[])
{
dfs g = new dfs(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);

35
Enrollment No. 190200107058 Name – Harshil Kaneria

g.addEdge(3, 3);

System.out.println(
"Following is Depth First Traversal "
+ "(starting from vertex 2)");

g.DFS(2);
}
}

Output:

Following is Depth First Traversal (starting from vertex 2)


2013

36

You might also like