0% found this document useful (0 votes)
10 views

Ada 9

Uploaded by

nikhilmahato526
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Ada 9

Uploaded by

nikhilmahato526
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

220860116009 Analysis and Design of Algorithms

Practical: 1
Aim: Measure execution time taken by a program in C & Java.

• In c language:
#include<stdio.h>
#include<conio.h>
#include<time.h>
void main()
{
clock_t start,end;
int a;
clrscr();
start = clock();
printf("Enter number: ");
scanf("%d",&a);
end = clock();
printf("%f seconds",(double)((end-start)/CLOCKS_PER_SEC));
getch();
}

Output:

1
220860116009 Analysis and Design of Algorithms

• In Java:

class Time{
public static void main(String[] args){
long start,end;
start = System.nanoTime();
int m=0;
for(int i=0;i<1000;i++){
m++;
}
System.out.println("Value:"+m);
end = System.nanoTime();
System.out.println("Execution time:"+(end-start)+"ns");
}
}
Output:

2
220860116009 Analysis and Design of Algorithms

Practical 2
Aim: Implementation and Time analysis of sorting algorithms: Bubble sort,
Selection sort, Insertion sort, Merge sort and Quicksort.
Bubble sort:
import java.util.*;
class Prac2a{
public static void BubbleSort(int[] a){
int n=a.length;
int temp=0;
for(int i=0;i<a.length-2;i++){
for(int j=0;j<a.length-i-1;j++){
if(a[j]>a[j+1]){
//swap elements
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
public static void main(String args[]){
long start,end;
System.out.print("input"+"\t\t\t\t"+"Sorted"+"\t\t\t"+"Random"+"\t\t\t\t\t"+"Reverse");
System.out.println();
System.out.println("------------------------------------------------------------------------------------
-------------------------------");
int input[]={10,50,100,500,1000,5000,10000,50000};
for(int n:input){
System.out.print(n+"\t\t\t\t");
//Sorted
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=i+1;
start=System.nanoTime();
BubbleSort(a);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t");
//Random
int b[]=new int[n];
for(int i=0;i<n;i++)

3
220860116009 Analysis and Design of Algorithms

b[i]=(int)(Math.random()*n+1);
start=System.nanoTime();
BubbleSort(b);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t\t\t");
//Reverse
int c[]=new int[n];
for(int i=n;i>0;i--)
c[i-1]=i;
start=System.nanoTime();
BubbleSort(c);
end=System.nanoTime();
System.out.println(end-start);
}
}
}
Output:

Selection sort:
import java.util.*;
class Prac2b {
public static void SelectionSort(int[] a){
int min,minx;
for(int i=0;i<a.length-2;i++){
min=i;
minx=a[i];
for(int j=i+1;j<a.length;j++){
if(a[j]<minx){
min=j;
minx=a[j];
}
}
a[min]=a[i];
a[i]=minx;
}
}
public static void main(String args[]){
long start,end;
System.out.print("input"+"\t\t\t\t\t"+"Sorted"+"\t\t\t\t"+"Random"+"\t\t\t\t"+"Reverse");

4
220860116009 Analysis and Design of Algorithms

System.out.println();
System.out.println("------------------------------------------------------------------------------------
-----------------------------");
int input[]={10,50,100,500,1000,5000,10000,50000};
for(int n:input){
System.out.print(n+"\t\t\t\t\t");
//Sorted
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=i+1;
start=System.nanoTime();
SelectionSort(a);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t\t");
//Random
int b[]=new int[n];
for(int i=0;i<n;i++)
b[i]=(int)(Math.random()*n+1);
start=System.nanoTime();
SelectionSort(b);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t\t");
//Reverse
int c[]=new int[n];
for(int i=n;i>0;i--)
c[i-1]=i;
start=System.nanoTime();
SelectionSort(c);
end=System.nanoTime();
System.out.println(end-start);
}
}
}
Output:

Insertion sort:
import java.util.*;
class Prac2c{
public static void InsertionSort(int a[]){

5
220860116009 Analysis and Design of Algorithms

int key,i,j;
for(i=1;i<a.length;i++){
key=a[i];
j=i-1;
while(j>=0 && key<a[j]){
a[j+1]=a[j];
j--;
}
a[j+1]=key;
}
}
public static void main(String args[]){
long start,end;
System.out.print("input"+"\t\t\t\t\t"+"Sorted"+"\t\t\t\t"+"Random"+"\t\t\t\t"+"Reverse");
System.out.println();
System.out.println("------------------------------------------------------------------------------------
------------------------------");
int input[]={10,50,100,500,1000,5000,10000,50000};
for(int n:input){
System.out.print(n+"\t\t\t\t\t");
//Sorted
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=i+1;
start=System.nanoTime();
InsertionSort(a);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t\t");
//Random
int b[]=new int[n];
for(int i=0;i<n;i++)
b[i]=(int)(Math.random()*n+1);
start=System.nanoTime();
InsertionSort(b);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t\t");
//Reverse
int c[]=new int[n];
for(int i=n;i>0;i--)
c[i-1]=i;
start=System.nanoTime();
InsertionSort(c);
end=System.nanoTime();
System.out.println(end-start);
6
220860116009 Analysis and Design of Algorithms

}
}
}
Output:

Merge sort:
import java.util.*;
class Prac2d{
public static void mergeSort(int a[], int low, int high){
int mid;
if(low<high){
mid=(low+high)/2;
mergeSort(a,low,mid);
mergeSort(a,mid+1,high);
combine(a,low,mid,high);
}
}
public static void combine(int a[],int low,int mid,int high){
int i,j,k;
i=low;
j=mid+1;
k=low;
int temp[] = new int[high+1];
while(i<=mid && j<=high){
if(a[i]<=a[j]){
temp[k]=a[i];
i=i+1;
k=k+1;
}
else{
temp[k]=a[j];
j=j+1;
k=k+1;
}
}
while (i<=mid){
temp[k]=a[i];
i=i+1;
k=k+1;
7
220860116009 Analysis and Design of Algorithms

}
while (j<=high){
temp[k]=a[j];
j=j+1;
k=k+1;
}
}
public static void main(String args[]){
long start,end;
System.out.print("input"+"\t\t\t\t"+"sorted"+"\t\t\t"+"random"+"\t\t\t\t\t"+"reverse");
System.out.println();
System.out.println("------------------------------------------------------------------------------------
-----------------------------");
int input[]={10,50,100,500,1000,5000,10000,50000};
for(int n:input){
System.out.print(n+"\t\t\t\t");
//Sorted
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=i+1;
start=System.currentTimeMillis();
mergeSort(a,0,n-1);
end=System.currentTimeMillis();
System.out.print((end-start)+"\t\t\t");
//Random
int b[]=new int[n];
for(int i=0;i<n;i++)
b[i]=(int)(Math.random()*n+1);
start=System.currentTimeMillis();
mergeSort(a,0,n-1);
end=System.currentTimeMillis();
System.out.print((end-start)+"\t\t\t\t\t");
//Reverse
int c[]=new int[n];
for(int i=n;i>0;i--)
c[i-1]=i;
start=System.currentTimeMillis();
mergeSort(a,0,n-1);
end=System.currentTimeMillis();
System.out.println(end-start);
}
}
}
Output:
8
220860116009 Analysis and Design of Algorithms

Quick sort:
import java.util.*;
class Prac2e{
public static void quickSort(int a[], int low, int high){
if (low < high){
int p = partition(a, low, high);
quickSort(a, low, p - 1);
quickSort(a, p + 1, high);
}
}
public static int partition(int ar[], int low, int high){
int pivot = ar[low];
int i = low;
int j = high;
while(i<=j){
while(ar[i]<=pivot)
i++;
while(ar[j]>pivot)
j--;
if(i<=j){
int temp=ar[i];
ar[i]=ar[j];
ar[j]=temp;
}
}
int temp = ar[j];
ar[j] = ar[low];
ar[low] = temp;
return j;
}
void printArr(int a[], int n){
int i;
for (i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
public static void main(String args[]){
long start,end;
System.out.print("input"+"\t\t\t\t"+"Sorted"+"\t\t\t"+"Random"+"\t\t\t\t\t"+"Reverse");

9
220860116009 Analysis and Design of Algorithms

System.out.println();
System.out.println("------------------------------------------------------------------------------------
--------------");
int input[]={10,50,100,500,1000,5000,10000,50000};
for(int n:input){
System.out.print(n+"\t\t\t\t");
//Sorted
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=i+1;
start=System.nanoTime();
quickSort(a,0,n-1);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t");
//Random
int b[]=new int[n];
for(int i=0;i<n;i++)
b[i]=(int)(Math.random()*n+1);
start=System.nanoTime();
quickSort(a,0,n-1);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t\t\t");
//Reverse
int c[]=new int[n];
for(int i=n;i>0;i--)
c[i-1]=i;
start=System.nanoTime();
quickSort(a,0,n-1);
end=System.nanoTime();
System.out.println(end-start);
}
}
}
Output:

10
220860116009 Analysis and Design of Algorithms

Practical 3
Aim: Implementation and Time analysis of linear and binary search algorithm.
import java.util.*;
class Prac3{
public static void binarySearch(int a[], int key, int low, int high){
int m = (low + high)/2;
while( low < high ){
if(key == a[m]){
System.out.println("Element is found at index:" +m);
}
else if(key < a[m]){
high = m - 1;
}
else{
low = m + 1;
}
}
}
public static void main(String args[]){
long start,end;
System.out.print("input"+"\t\t\t\t\t"+"Best"+"\t\t\t\t"+"Average"+"\t\t\t\t"+"Worst");
System.out.println();
System.out.println("------------------------------------------------------------------------------------
-----------------------------");
int input[]={10,50,100,500,1000,5000,10000,50000};
for(int n:input){
System.out.print(n+"\t\t\t\t\t");
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=(int)(Math.random()*n+1);
//Sorted
start=System.nanoTime();
binarySearch(a,0,n-1,a[0]);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t\t");
//Random
start=System.nanoTime();
binarySearch(a,0,n-1,a[n/2]);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t\t");
//Reverse
start=System.nanoTime();
11
220860116009 Analysis and Design of Algorithms

binarySearch(a,0,n-1,a[n-1]);
end=System.nanoTime();
System.out.println(end-start);
}
}
}
Linear.java
import java.util.*;
class Prac3a{
public static int linearSearch(int[] a, int key){
for(int i=0;i<a.length;i++){
if(a[i] == a[key]){
return i;
}
}
return -1;
}
public static void main(String args[]){
long start,end;
System.out.print("input"+"\t\t\t\t\t"+"Sorted"+"\t\t\t\t"+"Random"+"\t\t\t\t"+"Reverse");
System.out.println();
System.out.println("------------------------------------------------------------------------------------
----------------------------");
int input[]={10,50,100,500,1000,5000,10000,50000};
for(int n:input){
System.out.print(n+"\t\t\t\t\t");
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=(int)(Math.random()*n+1);
//Sorted
start=System.nanoTime();
linearSearch(a,0);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t\t");
//Random
start=System.nanoTime();
linearSearch(a,n/2);
end=System.nanoTime();
System.out.print((end-start)+"\t\t\t\t");
//Reverse
start=System.nanoTime();
linearSearch(a,n-1);
end=System.nanoTime();
System.out.println(end-start);
12
220860116009 Analysis and Design of Algorithms

}
}
}
Output:

13
220860116009 Analysis and Design of Algorithms

Practical 4
Aim: Implementation of max-heap sort algorithm.
public class HeapSort{
public void sort(int arr[]) {
int n = arr.length;
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[]) {
int n = arr.length;
for (int i=0; i<n; ++i)

14
220860116009 Analysis and Design of Algorithms

System.out.print(arr[i]+" ");
System.out.println();
}
// Driver program
public static void main(String args[]) {
int arr[] = {12, 11, 13, 5, 6, 7, 1, 3, 8, 9};
int n = arr.length;
System.out.println("Input array is");
printArray(arr);
HeapSort ob = new HeapSort();
ob.sort(arr);
System.out.println();
System.out.println("Sorted array is");
printArray(arr);
}
}
Output:

15
220860116009 Analysis and Design of Algorithms

Practical 5
Aim: Implementation and Time analysis of factorial program using iterative and
recursive method
import java.util.*;
import java.math.*;
class Prac5
{
public static BigInteger factorialI(int n)
{
BigInteger fact=BigInteger.ONE;
for(int i=1;i<=n;i++)
fact=fact.multiply(new BigInteger(String.valueOf(i)));
return fact;
}
public static BigInteger factorialR(int n)
{
if(n<1)
return BigInteger.ONE;
return (new BigInteger(String.valueOf(n))).multiply(factorialR(n-1));
}
public static void main(String args[])
{
long start,end;
int[] n={1,5,10,20,30,40,50,100,500,1000,3000};
System.out.println("Using Iterative method");
System.out.println("input"+"\t"+"time(microsec)");
System.out.println("------------------------------------------");
for(int temp:n)
{
start=System.nanoTime();
BigInteger ans=factorialI(temp);
end=System.nanoTime();
System.out.println(temp + "\t"+ (end-start)/1000);
}
System.out.println();
System.out.println("Using Recursive method");
System.out.println("input"+"\t"+"time(microsec)");
System.out.println("--------------------------------------------");
for(int temp:n)
{
start=System.nanoTime();
BigInteger ans1=factorialR(temp);
end=System.nanoTime();

16
220860116009 Analysis and Design of Algorithms

System.out.println(temp + "\t"+ (end-start)/1000);


}
}
}
Output:

17
220860116009 Analysis and Design of Algorithms

Practical 6
Aim: Implementation of making a change problem using dynamic programming
public class Prac6{
public static void main(String args[]){
int d[]={1,4,6};
int n=d.length;
int N=8;
int c[][]=new int[n+1][N+1];
for(int i=0;i<=n;i++){
c[i][0]=0;
}
for(int j=0;j<=N;j++){
c[0][j]=0;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=N;j++){
if(i==1){
c[i][j]=1+c[i][j-d[0]];
}
else if(j<d[i-1]){
c[i][j]=c[i-1][j];
}
else{
c[i][j]=min(c[i-1][j],1+c[i][j-d[i-1]]);
}
}
}
for(int i=0;i<=n;i++){
for(int j=0;j<=N;j++){
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
int i=n;
int j=N;
while(i>0 && j>0){
if(c[i][j] == c[i-1][j])
i--;
else{
System.out.println("Selected coins:" + d[i-1]);
j=j-d[i-1];
}
18
220860116009 Analysis and Design of Algorithms

}
}
public static int min(int a, int b){
if(a<=b){
return a;
}
else{
return b;
}
}
}
Output:

19
220860116009 Analysis and Design of Algorithms

Practical 7
Aim: Implementation of a knapsack problem using dynamic programming.
public class Prac7{
public static void main(String args[]){
int v[]={0,1,6,18,22,28};
int w[]={0,1,3,5,6,7};
int n=v.length-1;
int W=11;
int V[][]=new int[n+1][W+1];
for(int i=0;i<=n;i++){
V[i][0]=0;
}
for(int j=0;j<=W;j++){
V[0][j]=0;
}
for(int i=1;i<=n;i++){
for(int j=1;j<=W;j++){
if(j<w[i]){
V[i][j] = V[i-1][j];
}
else{
V[i][j] = Math.max(V[i-1][j],v[i]+V[i-1][j-w[i]]);
}
}
}
for(int i=0;i<=n;i++){
for(int j=0;j<=W;j++){
System.out.print(V[i][j]+"\t");
}
System.out.println();
}
System.out.println("Profit:" + V[n][W]);
int i=n;
int j=W;
while(i>0 || j>0){
if(V[i][j] == V[i-1][j])
i--;
else{
System.out.println("Value"+ v[i]+ " " +"Weight:"+w[i]);
j=j-w[i];
i--;
}
}

20
220860116009 Analysis and Design of Algorithms

}
public static int min(int a, int b){
if(a<=b){
return a;
}
else{
return b;
}
}
}
Output:

21
220860116009 Analysis and Design of Algorithms

Practical 8
Aim: Implementation of chain matrix multiplication using dynamic programming.
import java.util.Scanner;
public class MatrixChainMultiplication{
private int[][] m;
private int[][] s;
private int n;
public MatrixChainMultiplication(int[] p){
n = p.length - 1; // how many matrices are in the chain
m = new int[n + 1][n + 1]; // overallocate m, so that we don't use index// 0
s = new int[n + 1][n + 1]; // same for s
matrixChainOrder(p); } // run the dynamic-programming algorithm
private void matrixChainOrder(int[] p) { // Initial the cost for the empty subproblems.
for (int i = 1; i <= n; i++)
m[i][i] = 0;
for (int l = 2; l <= n; l++) {
for (int i = 1; i <= n - l + 1; i++){
int j = i + l - 1;
m[i][j] = Integer.MAX_VALUE;
for (int k = i; k < j; k++){
int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
if (q < m[i][j]){ // q is the best split for this subproblem so far.
m[i][j] = q;
s[i][j] = k; }}}}}
private String printOptimalParens(int i, int j){
if (i == j)
return "A[" + i + "]";
else
return "(" + printOptimalParens(i, s[i][j])+ printOptimalParens(s[i][j] + 1, j) + ")";}
public String toString(){
return printOptimalParens(1, n);}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array p[], which represents the chain of matrices such that the ith
matrix Ai is of dimension p[i-1] x p[i]");
System.out.println("Enter the total length: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter the dimensions: ");
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
MatrixChainMultiplication opudp = new MatrixChainMultiplication(arr);
System.out.println("Matrices are of order: ");
for (int i = 1; i < arr.length; i++){
System.out.println("A" + i + "-->" + arr[i - 1] + "x" + arr[i]);}
System.out.println(opudp.toString());
sc.close();

22
220860116009 Analysis and Design of Algorithms

}
}
Output:

23
220860116009 Analysis and Design of Algorithms

Practical 9
Aim: Implementation of a knapsack problem using greedy algorithm
import java.io.IOException;

import java.util.Scanner;

class Fractional_Knapsack

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

int i,j=0,max_qty,m,n;

float sum=0,max;

Scanner sc = new Scanner(System.in);

int array[][]=new int[2][20];

System.out.println("Enter no of items");

n=sc.nextInt();

System.out.println("Enter the weights of each items");

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

array[0][i]=sc.nextInt();

System.out.println("Enter the values of each items");

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

array[1][i]=sc.nextInt();

System.out.println("Enter maximum volume of knapsack :");

max_qty=sc.nextInt();

m=max_qty;

while(m>=0){

max=0;

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

24
220860116009 Analysis and Design of Algorithms

if(((float)array[1][i])/((float)array[0][i])>max) {

max=((float)array[1][i])/((float)array[0][i]);

j=i;

if(array[0][j]>m) {

System.out.println("Quantity of item number: " + (j+1) + " added is " +m);

sum+=m*max;

m=-1;

else {

System.out.println("Quantity of item number: " + (j+1) + " added is " +


array[0][j]);

m-=array[0][j];

sum+=(float)array[1][j];

array[1][j]=0;

System.out.println("The total profit is " + sum);

sc.close();

25
220860116009 Analysis and Design of Algorithms

26
220860116009 Analysis and Design of Algorithms

Practical 10

Aim: Implementation of Graph and Searching (DFS and BFS).


DFS

import java.io.*;

import java.util.*;

class Graph

private int V; // No. of vertices

Graph(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); // Add w to v's list.

void DFSUtil(int v,boolean visited[])

visited[v] = true;

System.out.print(v+" ");

Iterator<Integer> i = adj[v].listIterator();

while (i.hasNext())

27
220860116009 Analysis and Design of Algorithms

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[])

Graph g = new Graph(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 Depth First Traversal "+

"(starting from vertex 2)");

g.DFS(2);

28
220860116009 Analysis and Design of Algorithms

BFS

import java.io.*;

import java.util.*;

class Graph1

private int V; // No. of vertices

private LinkedList<Integer> adj[]; //Adjacency Lists

Graph1(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>();

29
220860116009 Analysis and Design of Algorithms

visited[s]=true;

queue.add(s);

while (queue.size() != 0)

// Dequeue a vertex from queue and print it

s = queue.poll();

System.out.print(s+" ");

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[])

Graph1 g = new Graph1(4);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

30
220860116009 Analysis and Design of Algorithms

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:

31
220860116009 Analysis and Design of Algorithms

Practical 11
Aim: Implement prim’s algorithm

import java.util.*;

import java.lang.*;

import java.io.*;

class MST

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 n, int graph[][])

System.out.println("Edge Weight");

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

System.out.println(parent[i]+" - "+ i+" "+

graph[i][parent[i]]);

32
220860116009 Analysis and Design of Algorithms

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; // Make key 0 so that this vertex is

// picked as first vertex

parent[0] = -1; // First node is always root of MST

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, V, graph);

33
220860116009 Analysis and Design of Algorithms

public static void main (String[] args)

/* Let us create the following graph

2 3

(0)--(1)--(2)

| /\ |

6| 8/ \5 |7

|/ \|

(3)-------(4)

9 */

MST t = new MST();

int graph[][] = new int[][] {{0, 2, 0, 6, 0},

{2, 0, 3, 8, 5},

{0, 3, 0, 0, 7},

{6, 8, 0, 0, 9},

{0, 5, 7, 9, 0},

};

t.primMST(graph);

OUTPUT:

34
220860116009 Analysis and Design of Algorithms

Practical 12

Aim: Implement kruskal’s algorithm.

import java.util.*;

import java.lang.*;

import java.io.*;

class Krushkal

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; // V-> no. of vertices & E->no.of edges

Edge edge[]; // collection of all edges

Krushkal(int v, int e)

V = v;

E = e;

edge = new Edge[E];

35
220860116009 Analysis and Design of Algorithms

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]; // Tnis will store the resultant MST

int e = 0; // An index variable, used for result[]

36
220860116009 Analysis and Design of Algorithms

int i = 0; // An index variable, used for sorted edges

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

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

subsets[v].parent = v;

subsets[v].rank = 0;

i = 0; // Index used to pick next edge

while (e < V - 1)

Edge next_edge = new 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 " +

37
220860116009 Analysis and Design of Algorithms

"the constructed MST");

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

System.out.println(result[i].src+" -- " +

result[i].dest+" == " + result[i].weight);

public static void main (String[] args)

/* Let us create following weighted graph


10
0--------1
| \ |
6| 5\ |15
| \|
2--------3
4 */
int V = 4; // Number of vertices in graph

int E = 5; // Number of edges in graph

Krushkal graph = new Krushkal(V, E);

// add edge 0-1

graph.edge[0].src = 0;

graph.edge[0].dest = 1;

graph.edge[0].weight = 10;

// add edge 0-2

graph.edge[1].src = 0;

graph.edge[1].dest = 2;

graph.edge[1].weight = 6;

// add edge 0-3

38
220860116009 Analysis and Design of Algorithms

graph.edge[2].src = 0;

graph.edge[2].dest = 3;

graph.edge[2].weight = 5;

// add edge 1-3

graph.edge[3].src = 1;

graph.edge[3].dest = 3;

graph.edge[3].weight = 15;

// add edge 2-3

graph.edge[4].src = 2;

graph.edge[4].dest = 3;

graph.edge[4].weight = 4;

graph.KruskalMST();

OUTPUT:

39
220860116009 Analysis and Design of Algorithms

Practical 13
Aim: Implement LCS problem.
import java.io.*;

import java.util.Scanner;

class LongestCommonSubsequence

static void lcs(String X, String Y, int m, int n)

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

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.charAt(i-1) == Y.charAt(j-1))

L[i][j] = L[i-1][j-1] + 1;

else

L[i][j] = Math.max(L[i-1][j], L[i][j-1]);

int index = L[m][n];

int temp = index;

char[] lcs = new char[index+1];

lcs[index] = '\0'; // Set the terminating character

int i = m, j = n;

while (i > 0 && j > 0)

40
220860116009 Analysis and Design of Algorithms

if (X.charAt(i-1) == Y.charAt(j-1))

lcs[index-1] = X.charAt(i-1);

// reduce values of i, j and index

i--;

j--;

index--;

else if (L[i-1][j] > L[i][j-1])

i--;

else

j--;

System.out.print("LCS of "+X+" and "+Y+" is ");

for(int k=0;k<=temp;k++)

System.out.print(lcs[k]);

System.out.print("and Length of LCS is "+temp);

public static void main (String[] args)

Scanner scan=new Scanner(System.in);

System.out.println("Enter first Sequence :");

String X = scan.nextLine();

System.out.println("Enter second Sequence :");

String Y = scan.nextLine();

41
220860116009 Analysis and Design of Algorithms

int m = X.length();

int n = Y.length();

lcs(X, Y, m, n);

OUTPUT:

42

You might also like