You are on page 1of 55

Ex.

No:1 IMPLEMENTATION OF FIBONACCI NUMBERUSING


Date: RECURSION

AIM:
To write a java program to implement Fibonacci number using Recursion.

ALGORITHM:
1. Read n value for computing in term in Fibonacci series call Fibonacci (n)
2. Fibonacci computes the nth Fibonacci number, for appropriate values of n.
Step1: If n = 0 then go to step2 else go to step3
3. return 0
4. If n = 1 then go to step4 else go to step 5 return 1
5. return (Fibonacci (n-1) + Fibonacci (n-2))

PROGRAM:
Class Node
{
int data;
Node left, right;
public Node(int key)
{
data = key;
left = right = null;
}
}
class Main
{
public static void preorder(Node root)
{
if (root == null) {
return;
}
System.out.print(root.data + " ");
preorder(root.left);
preorder(root.right);
}
public static void main(String[] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.left = new Node(7);
root.right.left.right = new Node(8);
preorder(root);
}

1
OUTPUT
12435876

RESULT:
Thus the java program to implement Fibonacci number using Recursion was written,
executed and verified successfully

2
Ex.No:2 IMPLEMENTATION OF FIBONACCI NUMBER USING
Date: ITERATION

AIM:
To write a java program to implement Fibonacci number using Iteration.

ALGORITHM:

1. Read n value for computing in term in Fibonacci series call Fibonacci (n)
2. Fibonacci computes the nth Fibonacci number, for appropriate values of n.
Step1: If n = 0 then go to step2 else go to step3
3. return 0
4. If n = 1 then go to step4 else go to step5 return 1
5. return(Fibonacci (n-1) + Fibonacci (n-2))

PROGRAM:
import java.util.Stack;
class Node
{
int data;
Node left, right;
public Node(int key)
{
data = key;
left = right = null;
}
}
class Main
{
public static void preorderIterative(Node root)
{
// return if the tree is empty
if (root == null) {
return;
}
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.empty())
{
Node curr = stack.pop();
System.out.print(curr.data + " ");
if (curr.right != null) {
stack.push(curr.right);
}
if (curr.left != null)
{
stack.push(curr.left);
}
}
}

3
public static void main(String[] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.left = new Node(7);
root.right.left.right = new Node(8);
preorderIterative(root);
}
}

OUTPUT
12435786

RESULT:
Thus the java program to implement Fibonacci number using Iteration was written,
executed and verified successfully

4
Ex.No:3a
IMPLEMENTATION OF MERGE SORT ANALYSIS
Date:

AIM:
To write a java program to implement merge sort analysis.

ALGORITHM:

1. If it is only one element in the list it is already sorted return.


2. Divide the list recursively into two halves until it can no more be divided.
3. Merge the smaller lists into new list in sorted order.
4. Stop the Program.

PROGRAM:

package com.java2 novice.sorting;


public class MyMergeSort
{
private int[] array;
private int[] tempMergArr;
private int length;
public static void main(String a[])
{
int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
MyMergeSort mms = new MyMergeSort();
mms.sort(inputArr);
for(int i:inputArr)
{
System.out.print(i); System.out.print();
}
}
public void sort(int inputArr[])
{
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex)
{
if (lowerIndex < higherIndex)
{
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(lowerIndex, middle);
doMergeSort(middle + 1, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex)
{
for (int i = lowerIndex; i <= higherIndex; i++)

5
{
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex)
{
if (tempMergArr[i] <= tempMergArr[j])
{
array[k] = tempMergArr[i];
i++;
}
else
{
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle) { array[k] = tempMergArr[i];
k++;
i++;
}
}
}

OUTPUT

4 11 23 28 43 45 65 77 89 98

RESULT:
Thus the java program to implement Merge Sort was written, executed and verified
successfully.

6
Ex.No:3b
IMPLEMENTATION OF QUICK SORT ANALYSIS
Date:

AIM:
To write a java program to implement quick sort analysis.

ALGORITHM:
1. Choose an element, called pivot, from the list. Generally pivot can be the middle
index element
2. Reorder the list so that all elements with values less than the pivot come before the
pivot
3. All elements with values greater than the pivot come after it (equal values can go
either way). After this partitioning, the pivot is in its final position. This is called the
partition operation.
4. Recursively apply the above steps to the sub-list of elements with smaller values
and separately the sub-list of elements with greater values.
5. Stop the Program.

PROGRAM:

package com.java2novice.sorting;
public class MyQuickSort
{
private int array[];
private int length;
public void sort(int[] inputArr)
{
if (inputArr == null || inputArr.length == 0)
{
return;
}
this.array = inputArr;
length = inputArr.length;
quickSort(0, length - 1);
}
private void quickSort(int lowerIndex, int higherIndex)
{
int i = lowerIndex;
int j = higherIndex;
// calculate pivot number, I am taking pivot as middle index number
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
// Divide into two arrays
while (i <= j)
{
while (array[i] < pivot)
{
i++;
}
while (array[j] > pivot)
{

7
j--;
}
if (i <= j)
{
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (lowerIndex < j) quickSort(lowerIndex, j);
if (i < higherIndex) quickSort(i, higherIndex);
}
private void exchangeNumbers(int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String a[])
{
MyQuickSort sorter = new MyQuickSort();
int[] input = {24,2,45,20,56,75,2,56,99,53,12};
sorter.sort(input);
for(int i:input)
{
System.out.print(i);
System.out.print(" ");
}
}
}

OUTPUT

2 2 12 20 24 45 53 56 56 75 99

RESULT:
Thus the java program to implement quick sort was written, executed and verified
successfully.

8
Ex.No:4
IMPLEMENTATION OF BINARY SEARCH TREE
Date:

AIM:
To write a java program for implementing Binary Search Tree.

ALGORITHM:
1. Read the search element from the user
2. Compare, the search element with the value of root node in the tree.
3. If both are matching, then display "Given node found" and terminate the function
4. If both are not matching, then check whether search element is smaller or larger
than that node value.
5. If search element is smaller, then continue the search process in left subtree.
6. If search element is larger, then continue the search process in right subtree.
7. Repeat the same until we found exact element or we completed with a leaf node
8. If we reach to the node with search value, then display "Element is found" and
terminate the function.
9. If we reach to a leaf node and it is also not matching, then display "Element not
found" and terminate the function.

PROGRAM:
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++) array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last= n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search ) first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " +
(middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;

9
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}

OUTPUT:
Enter The Number Of Elements 5
Enter 5 Integers
2
5
6
8
9
Enter Value To Find 5
5 Found At Location 2.

RESULT:

Thus the implementation of Binary Search tree was written, executed and verified
successfully.

10
Ex.No:5
RED-BLACK TREE IMPLEMENTATION
Date:

AIM:
To write a java program to implement Red-Black Tree.

ALGORITHM:
1. Check whether tree is Empty.
2. If tree is Empty then insert the newNode as Root node with color Black and exit
from the operation.
3. If tree is not Empty then insert the newNode as a leaf node with Red color.
4. If the parent of newNode is Black then exit from the operation.
5. If the parent of newNode is Red then check the color of parent node's sibling of
newNode.
6. If it is Black or NULL node then make a suitable Rotation and Recolor it.
7. If it is Red colored node then perform Recolor and Recheck it. Repeat the same
until tree becomes Red Black Tree.
PROGRAM:
import java.util.Scanner;
class RedBlackNode
{
RedBlackNode left, right;
int element;
int color;
public RedBlackNode(int theElement)
{
this( theElement, null, null );
}
public RedBlackNode(int theElement, RedBlackNode lt, RedBlackNode rt)
{
left = lt;
right = rt;
element = theElement;
color = 1;
}
}
class RBTree
{
private RedBlackNode current;
private RedBlackNode parent;
private RedBlackNode grand;
private RedBlackNode great;
private RedBlackNode header;
private static RedBlackNode nullNode;
static
{
nullNode = new RedBlackNode(0);
nullNode.left = nullNode;
nullNode.right = nullNode;

11
}
static final int BLACK = 1;
static final int RED = 0;
public RBTree(int negInf)
{
header = new RedBlackNode(negInf);
header.left = nullNode;
header.right = nullNode;
}
public boolean isEmpty()
{
return header.right == nullNode;
}
public void makeEmpty()
{
header.right = nullNode;
}
public void insert(int item )
{
current = parent = grand = header;
nullNode.element = item;
while (current.element != item)
{
great = grand;
grand = parent;
parent = current;
current = item < current.element ? current.left : current.right;
if (current.left.color == RED && current.right.color == RED)
handleReorient( item );
}
if (current != nullNode)
return;
current = new RedBlackNode(item, nullNode, nullNode);
if (item < parent.element)
parent.left = current;
else
parent.right = current;
handleReorient( item );
}
private void handleReorient(int item)
{
current.color = RED;
current.left.color = BLACK;
current.right.color = BLACK;
if (parent.color == RED)
{
grand.color = RED;
if (item < grand.element != item < parent.element)
parent = rotate( item, grand );
current = rotate(item, great );

12
current.color = BLACK;
}
header.right.color = BLACK;
}
private RedBlackNode rotate(int item, RedBlackNode parent)
{
if(item < parent.element)
return parent.left = item < parent.left.element ?
rotateWithLeftChild(parent.left) :
rotateWithRightChild(parent.left) ;
else
return parent.right = item < parent.right.element ?
rotateWithLeftChild(parent.right) :
rotateWithRightChild(parent.right);
}
private RedBlackNode rotateWithLeftChild(RedBlackNode k2)
{
RedBlackNode k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
return k1;
}
private RedBlackNode rotateWithRightChild(RedBlackNode k1)
{
RedBlackNode k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
return k2;
}
public int countNodes()
{
return countNodes(header.right);
}
private int countNodes(RedBlackNode r)
{
if (r == nullNode)
return 0;
else
{
int l = 1;
l += countNodes(r.left);
l += countNodes(r.right);
return l;
}
}
public boolean search(int val)
{
return search(header.right, val);
}
private boolean search(RedBlackNode r, int val)

13
{
boolean found = false;
while ((r != nullNode) && !found)
{
int rval = r.element;
if (val < rval)
r = r.left;
else if (val > rval)
r = r.right;
else
{
found = true;
break;
}
found = search(r, val);
}
return found;
}
public void inorder()
{
inorder(header.right);
}
private void inorder(RedBlackNode r)
{
if (r != nullNode)
{
inorder(r.left);
char c = 'B';
if (r.color == 0)
c = 'R';
System.out.print(r.element +""+c+" ");
inorder(r.right);
}
}
public void preorder()
{
preorder(header.right);
}
private void preorder(RedBlackNode r)
{
if (r != nullNode)
{
char c = 'B';
if (r.color == 0)
c = 'R';
System.out.print(r.element +""+c+" ");
preorder(r.left);
preorder(r.right);
}
}

14
public void postorder()
{
postorder(header.right);
}
private void postorder(RedBlackNode r)
{
if (r != nullNode)
{
postorder(r.left);
postorder(r.right);
char c = 'B';
if (r.color == 0)
c = 'R';
System.out.print(r.element +""+c+" ");
}
}
}
public class RedBlackTree
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of RedBlack Tree */
RBTree rbt = new RBTree(Integer.MIN_VALUE);
System.out.println("Red Black Tree Test\n");
char ch;
do
{
System.out.println("\nRed Black Tree Operations\n");
System.out.println("1. insert ");
System.out.println("2. search");
System.out.println("3. count nodes");
System.out.println("4. check empty");
System.out.println("5. clear tree");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
rbt.insert( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to search");
System.out.println("Search result : "+ rbt.search( scan.nextInt() ));
break;
case 3 :
System.out.println("Nodes = "+ rbt.countNodes());
break;
case 4 :

15
System.out.println("Empty status = "+ rbt.isEmpty());
break;
case 5 :
System.out.println("\nTree Cleared");
rbt.makeEmpty();
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
System.out.print("\nPost order : ");
rbt.postorder();
System.out.print("\nPre order : ");
rbt.preorder();
System.out.print("\nIn order : ");
rbt.inorder();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
}
while (ch == 'Y'|| ch == 'y');
}
}
OUTPUT
2.- Delete items
3.- Check items
4.- Print tree
5.- Delete tree
1
22 33 4 5 6 7 8 55 3 2 1 6 4 -999

Color: Red Key: 1 Parent: 2


Color: Black Key: 2 Parent: 3
Color: Black Key: 3 Parent: 5
Color: Black Key: 4 Parent: 3
Color: Red Key: 4 Parent: 4
Color: Black Key: 5 Parent: -1
Color: Black Key: 6 Parent: 7
Color: Red Key: 6 Parent: 6
Color: Red Key: 7 Parent: 22
Color: Black Key: 8 Parent: 7
Color: Black Key: 22 Parent: 5
Color: Black Key: 33 Parent: 22
Color: Red Key: 55 Parent: 33
1.- Add items
2.- Delete items
3.- Check items
4.- Print tree
5.- Delete tree
2
33 22 5 4 7 6 55 8 2 3 6 1 4 -999

16
Deleting item 33: deleted! Deleting item 22: deleted! Deleting item 5: deleted! Deleting item
4: deleted! Deleting item 7: deleted! Deleting item 6: deleted! Deleting item 55: deleted!
Deleting item 8: deleted! Deleting item 2: deleted! Deleting item 3: deleted! Deleting item 6:
deleted! Deleting item 1: deleted! Deleting item 4: deleted! 1.- Add items
2.- Delete items
3.- Check items
4.- Print tree
5.- Delete tree
4
1.- Add items
2.- Delete items
3.- Check items
4.- Print tree
5.- Delete tree

RESULT:
Thus the java program to implement Red Black Tree was executed and verified
successfully.

17
Ex.No:6
HEAP IMPLEMENTATION
Date:

AIM:

To write a java program for heap implementation.


ALGORITHM:

1. Call the buildMaxHeap() function on the list. Also referred to as heapify(), this
builds a heap from a list in O(n) operations.
2. Swap the first element of the list with the final element. Decrease the considered
range of the list by one.
3. Call the siftDown() function on the list to sift the new first element to its
appropriate index in the heap.
4. Go to step (2) unless the considered range of the list is one element.
5. The buildMaxHeap() operation is run once, and is O(n) in performance. The
siftDown() function is O(log n), and is called n times. Therefore, the performance
of this algorithm is O(n + n log n) = O(n log n).

PROGRAM:
import java.util.Scanner; class Heap
{
private int[] heapArray; private int maxSize; private int heapSize;
public Heap(int mx)
{
maxSize = mx; heapSize = 0;
heapArray = new int[maxSize];
}
public boolean isEmpty()
{
return heapSize == 0;
}
public boolean insert(int ele)
{
if (heapSize + 1 == maxSize) return false;
heapArray[++heapSize] = ele; int pos = heapSize;
while (pos != 1 && ele > heapArray[pos/2])
{
heapArray[pos] = heapArray[pos/2];
pos /=2;
}
heapArray[pos] = ele; return true;
}
public int remove()
{
int parent, child;
int item, temp;
if (isEmpty() )
throw new RuntimeException("Error : Heap empty!");
item = heapArray[1];

18
temp = heapArray[heapSize--];
parent = 1;
child = 2;
while (child <= heapSize)
{
if (child < heapSize && heapArray[child] < heapArray[child +1]) child++;
if (temp >= heapArray[child]) break;
heapArray[parent] = heapArray[child]; parent = child;
child *= 2;
}
heapArray[parent] = temp;
return item;
}
public void displayHeap()
{
System.out.print("\nHeap array: ");
for(int i = 1; i <= heapSize; i++)
System.out.print(heapArray[i] +" "); System.out.println("\n");
}
}
public class HeapTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in); System.out.println("Heap Test\n\n");
System.out.println("Enter size of heap");
Heap h = new Heap(scan.nextInt() );
char ch;
do
{
System.out.println("\nHeap Operations\n"); System.out.println("1.
insert ");
System.out.println("2. delete item with max key ");
System.out.println("3. check empty");
boolean chk;
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
chk = h.insert( scan.nextInt() );
if (chk)
System.out.println("Insertion successful\n");
else
System.out.println("Insertion failed\n");
break;
case 2 :
System.out.println("Enter integer element to delete");
if (!h.isEmpty())
h.remove(); else

19
System.out.println("Error. Heap is empty\n");
break;
case 3 :
System.out.println("Empty status = "+ h.isEmpty());
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
h.displayHeap();
System.out.println("\nDo you want to continue(Type y or n)\n"); ch =
scan.next().charAt(0);
}
while (ch == 'Y'|| ch == 'y');
}
}

OUTPUT
Enter size of heap
10
Heap Operations
1. insert
2. delete item with max key
3. check empty 1
Enter integer element to insert 7
Insertion successful Heap array: 7
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty 1
Enter integer element to insert 3
Insertion successful Heap array: 7 3
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty

Enter integer element to insert 2


Insertion successful Heap array: 7 3 2
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty 1
Enter integer element to insert 5
Insertion successful Heap array: 7 5 2 3
Do you want to continue (Type y or n) y
Heap Operations

20
1. insert
2. delete item with max key
3. check empty 1
Enter integer element to insert 8
Insertion successful Heap array: 8 7 2 3 5
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty 1
Enter integer element to insert 1
Insertion successful

Heap array: 8 7 2 3 5 1
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty 1
Enter integer element to insert 9
Insertion successful
Heap array: 9 7 8 3 5 1 2
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty 2
Enter integer element to delete Heap array: 8 7 2 3 5 1
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty 2
Enter integer element to delete Heap array: 7 5 2 3 1
Do you want to continue (Type y or n) y

Heap Operations
1. insert
2. delete item with max key
3. check empty 2
Enter integer element to delete Heap array: 5 3 2 1
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty 2
Enter integer element to delete Heap array: 3 1 2
Do you want to continue (Type y or n) y
Heap Operations
1. insert

21
2. delete item with max key
3. check empty 2
Enter integer element to delete Heap array: 2 1
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty 2
Enter integer element to delete Heap array: 1
Do you want to continue (Type y or n)

y
Heap Operations
1. insert
2. delete item with max key
3. check empty 2
Enter integer element to delete Heap array:
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty 2
Enter integer element to delete Error. Heap is empty
Heap array:
Do you want to continue (Type y or n) y
Heap Operations
1. insert
2. delete item with max key
3. check empty 3
Empty status = true Heap array:
Do you want to continue (Type y or n) n

RESULT:
Thus the heap implementation was written, executed and verified successfully.

22
Ex.No:7
FIBONACCI HEAP IMPLEMENTATION
Date:

AIM:

To write a java program for Fibonacci heap implement.

ALGORITHM:
1. Call the buildMinHeap() function on the list.
2. insert(x) inserts a node x into the heap.
3. minimum() returns the node in the heap with minimum key.
4. extractMin() deletes the node with minimum key from the heap.
5. union(H) merge heap H and create a new one.
6. decreaseKey(x,k) assigns to node x within the heap the new key value k, which is
assumed to be no greater than its current key value.
7. delete(x) deletes node x from the heap.

PROGRAM:
import java.util.*;
class FibonacciHeapNode
{
FibonacciHeapNode child, left, right, parent;
int element;
public FibonacciHeapNode(int element)
{
this.right = this; this.left = this; this.element = element;
}
}
class FibonacciHeap
{
private FibonacciHeapNode root; private int count;
public FibonacciHeap()
{
root = null; count = 0;
}
public boolean isEmpty()
{
return root == null;
}
public void clear()
{
root = null; count = 0;
}
public void insert(int element)
{
FibonacciHeapNode node = new FibonacciHeapNode(element);
node.element = element;
if (root != null)
{
}

23
else
node.left = root; node.right = root.right; root.right = node;
node.right.left = node;
if (element < root.element) root = node;
root = node;
count++;
}
public void display()
{
System.out.print("\nHeap = "); FibonacciHeapNode ptr = root;
if (ptr == null)
{
System.out.print("Empty\n");
return;
}
do
{
System.out.print(ptr.element +" ");
ptr = ptr.right;
}
while (ptr != root && ptr.right != null);
System.out.println();
}
}
public class FibonacciHeapTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("FibonacciHeap Test\n\n");
FibonacciHeap fh = new FibonacciHeap();
char ch;
do
{
System.out.println("\nFibonacciHeap Operations\n");
System.out.println("1. insert element ");
System.out.println("2. check empty");
System.out.println("3. clear");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter element");
fh.insert( scan.nextInt() );
break;
case 2 :
System.out.println("Empty status = "+ fh.isEmpty());
break;
case 3 :
fh.clear(); break;

24
default :
System.out.println("Wrong Entry \n ");
break;
}

fh.display();
System.out.println("\nDo you want to continue(Type y or n) n");
ch = scan.next().charAt(0);
}
while (ch == 'Y'|| ch == 'y');
}
}

OUTPUT
FibonacciHeap Test FibonacciHeap Operations
1. insert element
2. check empty
3. clear 1
Enter element 24
Heap = 24
Do you want to continue (Type y or n) y
FibonacciHeap Operations
1. insert element
2. check empty
3. clear 1
Enter element 6
Heap = 6 24
Do you want to continue (Type y or n) y
FibonacciHeap Operations
1. insert element
2. check empty
3. clear 1
Enter element 28
Heap = 6 28 24
Do you want to continue (Type y or n)
y
FibonacciHeap Operations
1. insert element
2. check empty
3. clear 1
Enter element 14
Heap = 6 14 28 24
Do you want to continue (Type y or n) y
FibonacciHeap Operations
1. insert element
2. check empty
3. clear 1
Enter element 63
Heap = 6 63 14 28 24
Do you want to continue (Type y or n) y

25
FibonacciHeap Operations
1. insert element
2. check empty
3. clear 2
Empty status = false Heap = 6 63 14 28 24
Do you want to continue (Type y or n) y
FibonacciHeap Operations
1. insert element
2. check empty
3. clear 2
Empty status = true Heap = Empty
Do you want to continue (Type y or n) n

RESULT:
Thus the Fibonacci heap implementation was written, executed and verified
successfully.

26
Ex.No:8a
GRAPH TRAVERSALS (DEPTH FIRST SEARCH)
Date:

AIM:

To write a java program to implement graph traversal by using depth first search.
ALGORITHM:

1. Start at some node, and is now our current node.


2. State that our current node is „visited‟.
3. Now look at all nodes adjacent to our current node.
4. If we see an adjacent node that has not been „visited‟, add it to the stack.
5. Then pop of the top node on the stack and traverse to it.
6. And go back to step 1.

PROGRAM:

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public class DFS
{
private Stack<Integer> stack;
public DFS()
{
stack = new Stack<Integer>();
}
public void dfs(int adjacency_matrix[][], int source)
{
int number_of_nodes = adjacency_matrix[source].length - 1;
int visited[] = new int[number_of_nodes + 1];
int element = source;
int i = source;
System.out.print(element + "\t"); visited[source] = 1;
stack.push(source);
while (!stack.isEmpty())
{
element = stack.peek();
i = element;
while (i <= number_of_nodes)
{
if (adjacency_matrix[element][i] == 1 && visited[i] ==0)
{
stack.push(i); visited[i] = 1; element = i;
i = 1;
System.out.print(element + "\t"); continue;
}
i++;
}

27
stack.pop();
}
}
public static void main(String...arg)
{
int number_of_nodes, source;
try
Scanner scanner = null;
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in);
number_of_nodes = scanner.nextInt();
int adjacency_matrix[][] = new
int[number_of_nodes+1][number_of_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacency_matrix[i][j] = scanner.nextInt();
System.out.println("Enter the source for the graph");
source = scanner.nextInt();
System.out.println("The DFS Traversal for the graph is given by ");
DFS dfs = new DFS(); dfs.dfs(adjacency_matrix, source);
}
catch(InputMismatchException inputMismatch)
{
System.out.println("Wrong Input format");
}
scanner.close();
}
}

OUTPUT
$javac DFS.java
$java DFS
Enter the number of nodes in the graph 4
Enter the adjacency matrix 0 1 0 1
0010
0101
0001
Enter the source for the graph 1
The DFS Traversal for the graph is given by 1 2 3 4

RESULT:
Thus the java program to implement depth first search was written and verified
successfully.

28
Ex.No:8b
GRAPH TRAVERSALS (BREADTH FIRST SEARCH)
Date:

AIM:

To write a program to implement graph traversals by using breadth first search.

ALGORITHM:

1. Define a Queue of size total number of vertices in the graph.


2. Select any vertex as starting point for traversal. Visit that vertex and insert it into
the Queue.
3. Visit all the adjacent vertices of the vertex which is at front of the Queue which is
not visited and insert them into the Queue.
4. When there is no new vertex to be visit from the vertex at front of the Queue then
delete that vertex from the Queue.
5. Repeat step 3 and 4 until queue becomes empty.

PROGRAM
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue; import java.util.Scanner;
public class BFS
{
private Queue<Integer> queue; public BFS()
queue = new LinkedList<Integer>();
}
public void bfs(int adjacency_matrix[][], int source)
{
int number_of_nodes = adjacency_matrix[source].length - 1;
int[] visited = new int[number_of_nodes + 1];
int i, element;
visited[source] = 1; queue.add(source);
while (!queue.isEmpty())
{
element = queue.remove(); i = element;
System.out.print(i + "\t");
while (i <= number_of_nodes)
{
if (adjacency_matrix[element][i] == 1 && visited[i] ==0)
{
queue.add(i); visited[i] = 1;
}
i++;
}
}
}
public static void main(String... arg)
{
int number_no_nodes, source; Scanner scanner = null;

29
try
{
System.out.println("Enter the number of nodes in the graph");
scanner = new Scanner(System.in); number_no_nodes =
scanner.nextInt();
int adjacency_matrix[][] = new int[number_no_nodes + 1]
[number_no_nodes + 1];
System.out.println("Enter the adjacency matrix");
for (int i = 1; i <= number_no_nodes; i++)
for (int j = 1; j <= number_no_nodes; j++) adjacency_matrix[i][j] =
scanner.nextInt();
System.out.println("Enter the source for the graph");
source = scanner.nextInt();
System.out.println("The BFS traversal of the graph is ");
BFS bfs = new BFS();
bfs.bfs(adjacency_matrix, source);
}
catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scanner.close();
}
}

OUTPUT
$javac BFS.java
$java BFS
Enter the number of nodes in the graph 4
Enter the adjacency matrix 0 1 0 1
0010
0101
0001
Enter the source for the graph 1
The BFS traversal of the graph is 1 2 4 3

RESULT:
Thus the java program to implement graph traversal by using breadth first search was
written, executed and verified successfully.

30
Ex.No:9a SPANNING TREE IMPLEMENTATION
Date: (KRUSKAL’S ALGORITHM)

AIM:
To write a java program to implement spanning tree implementation using kruskal‟s
algorithm.

ALGORITHM:

1. Create a graph F, where each vertex in the graph is a separate tree.


2. Create a set S containing all the edges in the graph.
3. While S is nonempty and F is not yet spanning.
Remove an edge with minimum weight from S.
`3.2. If the removed edge connects two different trees then add it to the forest F,
combining two trees into a single tree.

PROGRAM
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class KruskalAlgorithm
{
private List<Edge> edges; private int numberOfVertices;
public static final int MAX_VALUE = 999; private int visited[];
private int spanning_tree[][];
public KruskalAlgorithm(int numberOfVertices)
{
+ 1];
}
this.numberOfVertices = numberOfVertices; edges = new LinkedList<Edge>();
visited = new int[this.numberOfVertices + 1];
spanning_tree = new int[numberOfVertices + 1][numberOfVertices
public void kruskalAlgorithm(int adjacencyMatrix[][])
{
boolean finished = false;
for (int source = 1; source <= numberOfVertices; source++)
{
for (int destination = 1; destination <= numberOfVertices;destination++)
if (adjacencyMatrix[source][destination] != MAX_VALUE && source !=
estination)
{
Edge edge = new Edge(); edge.sourcevertex = source; edge.destinationvertex
= destination;
edge.weight = adjacencyMatrix[source][destination];
adjacencyMatrix[destination][source] = MAX_VALUE; edges.add(edge);
}
}

31
}
Collections.sort(edges, new EdgeComparator()); CheckCycle checkCycle = new
CheckCycle();
for (Edge edge : edges)
{
spanning_tree[edge.sourcevertex][edge.destinationvertex] =
edge.weight;
spanning_tree[edge.destinationvertex][edge.sourcevertex]
=edge.weight;
if (checkCycle.checkCycle(spanning_tree, edge.sourcevertex))
{
spanning_tree[edge.sourcevertex][edge.destinationvertex] = 0;
spanning_tree[edge.destinationvertex][edge.sourcevertex]= 0;
edge.weight = -1; continue;
}
visited[edge.sourcevertex] = 1;
visited[edge.destinationvertex] = 1;
for (int i = 0; i < visited.length; i++)
{
if (visited[i] == 0)
{
finished = false; break;
} else
{
finished = true;
}
}
if (finished) break;
}
System.out.println("The spanning tree is "); for (int i = 1; i <=
numberOfVertices; i++)
System.out.print("\t" + i); System.out.println();
for (int source = 1; source <= numberOfVertices; source++)
{
System.out.print(source + "\t");
for (int destination = 1; destination <= numberOfVertices; destination++)
{
"\t");
System.out.print(spanning_tree[source][destination] +
}
System.out.println();
}
}
public static void main(String... arg)
{
int adjacency_matrix[][]; int number_of_vertices;
Scanner scan = new Scanner(System.in); System.out.println("Enter the
number of vertices"); number_of_vertices = scan.nextInt(); adjacency_matrix
= new int[number_of_vertices +1][number_of_vertices + 1];

32
System.out.println("Enter the Weighted Matrix for the graph"); for (int i = 1; i
<= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt(); if (i == j)
{
adjacency_matrix[i][j] = 0; continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = MAX_VALUE;
}
}
}
KruskalAlgorithm kruskalAlgorithm = new KruskalAlgorithm(number_of_vertices);
kruskalAlgorithm.kruskalAlgorithm(adjacency_matrix); scan.close();
}
}
class Edge
{
int sourcevertex;
int destinationvertex; int weight;
}
class EdgeComparator implements Comparator<Edge>
{
@Override
public int compare(Edge edge1, Edge edge2)
{
if (edge1.weight < edge2.weight) return -1;
if (edge1.weight > edge2.weight) return 1;
return 0;
}
}
class CheckCycle
{
private Stack<Integer> stack; private int adjacencyMatrix[][];
public CheckCycle()
{
stack = new Stack<Integer>();
}
public boolean checkCycle(int adjacency_matrix[][], int source)
{
boolean cyclepresent = false;
int number_of_nodes = adjacency_matrix[source].length - 1;
+ 1];
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes
for (int sourcevertex = 1; sourcevertex <= number_of_nodes;
sourcevertex++)
{

33
for (int destinationvertex = 1; destinationvertex <= number_of_nodes; destinationvertex++)
{
adjacencyMatrix[sourcevertex][destinationvertex] =
adjacency_matrix[sourcevertex[destinationvertex];
}
}
int visited[] = new int[number_of_nodes + 1]; int element = source;
int i = source; visited[source] = 1; stack.push(source);
while (!stack.isEmpty())
{
element = stack.peek(); i = element;
while (i <= number_of_nodes)
{
if (adjacencyMatrix[element][i] >= 1 && visited[i] ==1)
{
if (stack.contains(i))
{
cyclepresent = true; return cyclepresent;
}
}
==0)
labelled;
if (adjacencyMatrix[element][i] >= 1 && visited[i]
{
stack.push(i); visited[i] = 1;
adjacencyMatrix[element][i] = 0;// mark as
adjacencyMatrix[i][element] = 0; element = i;
i = 1;
continue;
}
i++;
}
stack.pop();
}
return cyclepresent;
}
}

OUTPUT
$javac KruskalAlgorithm.java
$java KruskalAlgorithm Enter the number of vertices 6
Enter the Weighted Matrix for the graph 0 6 8 6 0 0
6 0 0 5 10 0
800753
657000
0 10 5 0 0 3
003030
The spanning tree is
1
2

34
3
4
5
6
1
0
6
0
0
0
0
2
6
0
0
5
0
0
3
0
0
0
7
0
3
4
0
5
7
0
0
0
5
0
0
0
0
0
3
6
0
0
3
0
3
0

RESULT:
Thus the Spanning tree implementation using kruskal‟s algorithm was written,
executed and verified successfully.

35
Ex.No:9b
SPANNING TREE IMPLEMENTATION (PRIM’S ALGORITHM)
Date:

AIM:

To write a java program to implement spanning tree implementation using Prim‟s


algorithm.
ALGORITHM:

1. Create a set mstSet that keeps track of vertices already included in MST.
2. Assign a key value to all vertices in the input graph. Initialize all key values as
INFINITE.
3. Assign key value as 0 for the first vertex so that it is picked first.
4. While mstSet doesn‟t include all vertices
Pick a vertex u which is not there in mstSet and has minimum key value.
Include u to mstSet.
Update key value of all adjacent vertices of u. To update the key values, iterate
through all adjacent vertices. For every adjacent vertex v, if weight of edge u-v is
less than the previous key value of v, update the key value as weight of u-v.

PROGRAM:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Prims
{
private boolean unsettled[];
private boolean settled[];
private int numberofvertices;
private int adjacencyMatrix[][];
private int key[];
public static final int INFINITE = 999;
private int parent[];
public Prims(int numberofvertices)
{
this.numberofvertices = numberofvertices; unsettled = new
boolean[numberofvertices + 1]; settled = new boolean[numberofvertices + 1];
adjacencyMatrix = new int[numberofvertices +1] [numberofvertices + 1];
key = new int[numberofvertices + 1]; parent = new int[numberofvertices + 1];
}
public int getUnsettledCount(boolean unsettled[])
{
int count = 0;
for (int index = 0; index < unsettled.length; index++)
{
if (unsettled[index])
{
count++;
}
}
return count;

36
}
public void primsAlgorithm(int adjacencyMatrix[][])
{
int evaluationVertex;
for (int source = 1; source <= numberofvertices; source++)
{
for (int destination = 1; destination <= numberofvertices; destination++)
{
this.adjacencyMatrix[source][destination] =
adjacencyMatrix[source][destination];
}
}
for (int index = 1; index <= numberofvertices; index++)
{
key[index] = INFINITE;
}
key[1] = 0; unsettled[1] = true; parent[1] = 1;
while (getUnsettledCount(unsettled) != 0)
{
evaluationVertex = getMimumKeyVertexFromUnsettled(unsettled);
unsettled[evaluationVertex] = false; settled[evaluationVertex] = true;
evaluateNeighbours(evaluationVertex);
}
}
private int getMimumKeyVertexFromUnsettled(boolean[] unsettled2)
{
int min = Integer.MAX_VALUE; int node = 0;
for (int vertex = 1; vertex <= numberofvertices; vertex++)
{
if (unsettled[vertex] == true && key[vertex] < min)
{
node = vertex;
min = key[vertex];
}
}
return node;
}
public void evaluateNeighbours(int evaluationVertex)
{
for (int destinationvertex = 1; destinationvertex <= numberofvertices;
destinationvertex++)
{
if (settled[destinationvertex] == false)
{
!= INFINITE)
if(adjacencyMatrix[evaluationVertex][destinationvertex]
{
if(adjacencyMatrix[evaluationVertex][destinationvertex] < key[destinationvertex])
{
key[destinationvertex] = adjacencyMatrix[evaluationVertex][destinationvertex];

37
parent[destinationvertex] = evaluationVertex;
}
unsettled[destinationvertex] = true;
}
}
}
}
public void printMST()
{
System.out.println("SOURCE : DESTINATION = WEIGHT");
for (int vertex = 2; vertex <= numberofvertices; vertex++)
{
System.out.println(parent[vertex] + "\t:\t" + vertex
+"\t=\t"+ adjacencyMatrix[parent[vertex]][vertex]);
}
}
public static void main(String... arg)
{
int adjacency_matrix[][]; int number_of_vertices;
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices"); number_of_vertices =
scan.nextInt(); adjacency_matrix = new int[number_of_vertices +
1] [number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for
thegraph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt(); if (i == j)
{
adjacency_matrix[i][j] = 0; continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = INFINITE;
}
}
}
Prims prims = new Prims(number_of_vertices);
prims.primsAlgorithm(adjacency_matrix);
prims.printMST();
}
catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();}}

38
OUTPUT
$javac Prims.java
$java Prims
Enter the number of vertices 5
Enter the Weighted Matrix for the graph
040
0
5
403
6
1
030
6
2
066
0
7
512
7
0
SOURCE
:
DESTINATION
=
WEIGHT
1
:
2
=
4
5
:
3
=
2
2
:
4
=
6
2
:
5
=
1

RESULT:
Thus the Spanning tree implementation using prim‟s algorithm was written, executed
and verified successfully.

39
EX No:10a SHORTEST PATH ALGORITHMS
DATE: (DIJKSTRA’S ALGORITHM)

AIM:

To write a java program to implement Dijkstra‟s Algorithm.


ALGORITHM:

1. Initialization of all nodes with distance "infinite"; initialization of the starting node
with 0
2. Marking of the distance of the starting node as permanent, all other distances as
temporarily.
3. Setting of starting node as active.
4. Calculation of the temporary distances of all neighbour nodes of the active node by
summing up its distance with the weights of the edges.
5. If such a calculated distance of a node is smaller as the current one, update the
distance and set the current node as antecessor. This step is also called update and
is Dijkstra's central idea.
6. Setting of the node with the minimal temporary distance as active. Mark its
distance as permanent.
7. Repeating of steps 4 to 7 until there aren't any nodes left with a permanent distance,
which neighbours still have temporary distances.

PROGRAM:
import java.util.HashSet;
import java.util.InputMismatchException; import java.util.Iterator;
import java.util.Scanner; import java.util.Set;
public class DijkstraAlgorithmSet
{
private int distances[]; private Set<Integer> settled; private Set<Integer> unsettled;
private int number_of_nodes;
private int adjacencyMatrix[][];
public DijkstraAlgorithmSet(int number_of_nodes)
{
+ 1];
}
this.number_of_nodes = number_of_nodes; distances = new int[number_of_nodes + 1];
settled = new HashSet<Integer>(); unsettled = new HashSet<Integer>();
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++) adjacencyMatrix[i][j] =
adjacency_matrix[i][j];
for (int i = 1; i <= number_of_nodes; i++)
{
distances[i] = Integer.MAX_VALUE;
}
unsettled.add(source); distances[source] = 0; while (!unsettled.isEmpty())

40
{
evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
unsettled.remove(evaluationNode); settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getNodeWithMinimumDistanceFromUnsettled()
{
int min ;
int node = 0;
Iterator<Integer> iterator = unsettled.iterator(); node = iterator.next();
min = distances[node];
for (int i = 1; i <= distances.length; i++)
{
if (unsettled.contains(i))
{
if (distances[i] <= min)
{
min = distances[i]; node = i;
}
}
}
return node;
}
private void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1; int newDistance = -1;
for (int destinationNode = 1; destinationNode
<=number_of_nodes; destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode]
!=Integer.MAX_VALUE)
{
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] +
edgeDistance;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
}
unsettled.add(destinationNode);
}
}
}
}
public static void main(String... arg)
{
int adjacency_matrix[][]; int number_of_vertices; int source = 0;

41
Scanner scan = new Scanner(System.in); try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt(); adjacency_matrix = new int[number_of_vertices
+1][number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for
thegraph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt(); if (i == j)
{
adjacency_matrix[i][j] = 0; continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
System.out.println("Enter the source "); source = scan.nextInt();
DijkstraAlgorithmSet dijkstrasAlgorithm = new
DijkstraAlgorithmSet(number_of_vertices);
dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix,source);
number_of_vertices = scan.nextInt(); adjacency_matrix = new int[number_of_vertices
+1][number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for
thegraph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt(); if (i == j)
adjacency_matrix[i][j] = 0; continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
System.out.println("Enter the source "); source = scan.nextInt();
DijkstraAlgorithmSet dijkstrasAlgorithm = new
DijkstraAlgorithmSet(number_of_vertices);
dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix,source);
1; i++)
System.out.println("The Shorted Path to all nodes are "); for (int i = 1; i <=
dijkstrasAlgorithm.distances.length -
{

42
System.out.println(source + " to " + i + " is
"+dijkstrasAlgorithm.distances[i]);
}
}
catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}

OUTPUT
$javac DijkstraAlgorithmSet.java
$java DijkstraAlgorithmSet Enter the number of vertices 5
Enter the Weighted Matrix for the graph 0 9 6 5 3
00000
02040
00000
00000
Enter the source 1
The Shorted Path to all nodes are
1 to 1 is 0
1 to 2 is 8
1 to 3 is 6
1 to 4 is 5
1 to 5 is 3

RESULT:
Thus the java program to implement Dijkstra‟s Algorithm was executed and verified
successfully.

43
Ex.No:10b SHORTEST PATH ALGORITHMS
Date: (BELLMANN FORD ALGORITHM)

AIM:
To write a java program to implement Bellmann Ford algorithm.

ALGORITHM:
1. Start with the weighted graph
2. Choose the starting vertex and assign infinity path values to all other vertex
3. Visit each edge and relax the path distance if they are inaccurate
4. We need to do this V times because in the worst case the vertex path length might
need to be readjusted V times
5. Notice how the vertex at the top right corner had its path length adjusted
6. After all vertices have their path lengths we check if a negative cycle is present
.
PROGRAM:
import java.util.Scanner; public class BellmanFord
{
private int distances[]; private int numberofvertices;
public static final int MAX_VALUE = 999;
public BellmanFord(int numberofvertices)
{
this.numberofvertices = numberofvertices; distances = new int[numberofvertices + 1];
}
public void BellmanFordEvaluation(int source, int adjacencymatrix[][])
{
for (int node = 1; node <= numberofvertices; node++)
{
distances[node] = MAX_VALUE;
}
distances[source] = 0;
for (int node = 1; node <= numberofvertices - 1; node++)
{
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)
{
MAX_VALUE)
if (adjacencymatrix[sourcenode][destinationnode] !=
{
if (distances[destinationnode] >distances[sourcenode]+
adjacencymatrix[sourcenode][destinationnode])
distances[destinationnode] =
distances[sourcenode]+adjacencymatrix[sourcenode][destinationnode];
}
}
}
}
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)

44
{
for (int destinationnode = 1; destinationnode <=
numberofvertices; destinationnode++)
{
MAX_VALUE)
if (adjacencymatrix[sourcenode][destinationnode] !=
{
if (distances[destinationnode] >distances[sourcenode]+
adjacencymatrix[sourcenode][destinationnode])
System.out.println("The Graph contains negative
egde cycle");
}
}
}
for (int vertex = 1; vertex <= numberofvertices; vertex++)
{
System.out.println("distance of source " + source + " to "+ vertex + " is " +
distances[vertex]);
}
}
public static void main(String... arg)
{
int numberofvertices = 0; int source;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of vertices"); numberofvertices =
scanner.nextInt();
int adjacencymatrix[][] = new int[numberofvertices + 1][numberofvertices + 1];
System.out.println("Enter the adjacency matrix");
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
for (int destinationnode = 1; destinationnode <= numberofvertices;
destinationnode++)
{
adjacencymatrix[sourcenode][destinationnode] = scanner.nextInt();
if (sourcenode == destinationnode)
{
adjacencymatrix[sourcenode][destinationnode] = 0; continue;
}
if (adjacencymatrix[sourcenode][destinationnode] == 0)
{
adjacencymatrix[sourcenode][destinationnode] =
MAX_VALUE;
}
}
}
System.out.println("Enter the source vertex");
source = scanner.nextInt();
}
}

45
OUTPUT
$javac BellmanFord.java
$java BellmanFord
Enter the number of vertices 6
Enter the adjacency matrix 0 4 0
0 -1 0
0 0 -1 0 -2 0
000000
000000
0 0 0 -5 0 3
000000
Enter
1
the source vertex
distance of source
1 to 1 is
0
distance of source 1 to 2 is 4
distance of source 1 to 3 is 3
distance of source 1 to 4 is -6
distance of source 1 to 5 is -1
distance of source 1 to 6 is 2

RESULT:
Thus the java program to implement Bellmann Ford Algorithm was written,
executed and verified successfully.

46
Ex.No:11
MATRIX CHAIN MULTIPLICATION
Date:

AIM:
To write a java program to implement Matrix Chain Multiplication.
ALGORITHM:
1. A chain of matrices to be multiplied is given as input.
2. For a sequence A1,A2,A3,A4 of 4 matrices, there are 5 different orderings=5
different parenthesization.
i) (A1,(A2(A3 A4)))
ii) (A1((A2 A3)A4))
iii) ((A1 A2)(A3 A4))
iv) ((A1(A2 A3))A4)
v) (((A1 A2)A3)A4)
3. Matrix_Multiply(A,B)
If coloumns[A]!=rows[B]
Then error “incomplete dimensions”
Else for i <- 1 to rows[A]
Do for j <- 1 to columns[B]
Do c[I,j] <- 0
For k<- 1 to columns[A]
Do c[i,j]=C[i,j]+A[i,k]+B[i,j]
Return c
4. A parenthesizing of the chain of the matrices is obtained as output.

PROGRAM:
import java.util.Scanner;
public class OptimalParanthesizationUsingDP
{
private int[][] m;
private int[][] s;
private int n;
public OptimalParanthesizationUsingDP(int[] p)
{
index
}
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
// 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;
// Solve for chains of increasing length l.
for (int l = 2; l<= n; l++)
{
for (int i = 1; i <= n - l + 1; i++)

47
{
int j = i + l - 1;
m[i][j] = Integer.MAX_VALUE;
// Check each possible split to see if it's better
// than all seen so far. 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(); OptimalParanthesizationUsingDP opudp =new
OptimalParanthesizationUsingDP(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();
}
}

OUTPUT
$ javac OptimalParanthesizationUsingDP.java
$ java OptimalParanthesizationUsingDP
Enter the array p[], which represents the chain of matrices such that the ith matrix Ai is of
dimension p[i-1] x

48
p[i]
Enter the total length: 5
Enter the dimensions: 2 4 5 2 1
Matrices are of order: A1-->2x4
A2-->4x5 A3-->5x2
A4-->2x1
(A[1](A[2](A[3]A[4])))

RESULT:
Thus the java program to implement Matrix Chain Multiplication was written, executed
and verified successfully.

49
Ex.No:12a
ACTIVITY SELECTION
Date:

AIM:

To write a java program to implement Activity Selection.

ALGORITHM:
1. Sort the activities as per finishing time in ascending order
2. Select the first activity
3. Select the new activity if its starting time is greater than or equal to the previously
selected activity
4. REPEAT step 3 till all activities are checked

PROGRAM:
import java.util.*;
import java.util.stream.Collectors;
class Pair
{
private int start, finish;
public Pair(int start, int finish)
{
this.start = start;
this.finish = finish;
}
public int getFinish() {
return finish;
}
public int getStart() {
return start;
}
@Override
public String toString() {
return "(" + getStart() + ", " + getFinish() + ")";
}
}
class Main
{
// Activity selection problem
public static List<Pair> selectActivity(List<Pair> activities)
{
int k = 0;
// set to store the selected activities index
Set<Integer> result = new HashSet<>();
// select 0 as the first activity
if (activities.size() > 0) {
result.add(0);
}
// sort the activities according to their finishing time
Collections.sort(activities, Comparator.comparingInt(Pair::getFinish));

50
// start iterating from the second element of the
// list up to its last element
for (int i = 1; i < activities.size(); i++)
{
// if the start time of the i'th activity is greater or equal
// to the finish time of the last selected activity, it
// can be included in the activities list
if (activities.get(i).getStart() >= activities.get(k).getFinish())
{
result.add(i);
k = i; // update `i` as the last selected activity
}
}
return result.stream()
.map(activities::get)
.collect(Collectors.toList());
}
public static void main(String[] args)
{
// List of given jobs. Each job has an identifier, a deadline, and a
// profit associated with it
List<Pair> activities = Arrays.asList(new Pair(1, 4), new Pair(3, 5),
new Pair(0, 6), new Pair(5, 7), new Pair(3, 8),
new Pair(5, 9), new Pair(6, 10), new Pair(8, 11),
new Pair(8, 12), new Pair(2, 13), new Pair(12, 14));
List<Pair> result = selectActivity(activities);
System.out.println(result);
}
}

OUTPUT:
[(1, 4), (5, 7), (8, 11), (12, 14)]

RESULT:
Thus the java program to implement activity selection was executed and verified
successfully.

51
Ex.No:12b
HUFFMAN CODING
Date:

AIM:

To write a java program to implement Huffman Coding

ALGORITHM:

1. Sort the message ensemble by decreasing probability.


2. N is the cardinal of the message ensemble (number of different messages).
3. Compute the integer n_0 such as 2<=n_0<=D and (N-n_0)/(D-1) is integer.
4. Select the n_0 least probable messages, and assign them each a digit code.
5. Substitute the selected messages by a composite message summing their
probability, and re-order it.
6. While there remains more than one message, do steps thru 8.
7. Select D least probable messages, and assign them each a digit code.
8. Substitute the selected messages by a composite message summing their
probability, and re-order it.
9. The code of each message is given by the concatenation of the code digits of the
aggregate they've been put in.

PROGRAM:
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
// A Tree node
class Node
{
Character ch;
Integer freq;
Node left = null, right = null;
Node(Character ch, Integer freq)
{
this.ch = ch;
this.freq = freq;
}
public Node(Character ch, Integer freq, Node left, Node right)
{
this.ch = ch;
this.freq = freq;
this.left = left;
this.right = right;
}
}
class Main
{
// Traverse the Huffman Tree and store Huffman Codes in a map.
public static void encode(Node root, String str,

52
Map<Character, String> huffmanCode)
{
if (root == null) {
return;
}
// Found a leaf node
if (isLeaf(root)) {
huffmanCode.put(root.ch, str.length() > 0 ? str : "1");
}
encode(root.left, str + '0', huffmanCode);
encode(root.right, str + '1', huffmanCode);
}
// Traverse the Huffman Tree and decode the encoded string
public static int decode(Node root, int index, StringBuilder sb)
{
if (root == null) {
return index;
}
// Found a leaf node
if (isLeaf(root))
{
System.out.print(root.ch);
return index;
}
index++;
root = (sb.charAt(index) == '0') ? root.left : root.right;
index = decode(root, index, sb);
return index;
}
// Utility function to check if Huffman Tree contains only a single node
public static boolean isLeaf(Node root) {
return root.left == null && root.right == null;
}
// Builds Huffman Tree and decodes the given input text
public static void buildHuffmanTree(String text)
{
// Base case: empty string
if (text == null || text.length() == 0) {
return;
}
// Count the frequency of appearance of each character
// and store it in a map
Map<Character, Integer> freq = new HashMap<>();
for (char c: text.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
// create a priority queue to store live nodes of the Huffman tree.
// Notice that the highest priority item has the lowest frequency
PriorityQueue<Node> pq;
pq = new PriorityQueue<>(Comparator.comparingInt(l -> l.freq));

53
// create a leaf node for each character and add it
// to the priority queue.
for (var entry: freq.entrySet()) {
pq.add(new Node(entry.getKey(), entry.getValue()));
}
// do till there is more than one node in the queue
while (pq.size() != 1)
{
// Remove the two nodes of the highest priority
// (the lowest frequency) from the queue
Node left = pq.poll();
Node right = pq.poll();
// create a new internal node with these two nodes as children
// and with a frequency equal to the sum of both nodes'
// frequencies. Add the new node to the priority queue.
int sum = left.freq + right.freq;
pq.add(new Node(null, sum, left, right));
}
// `root` stores pointer to the root of Huffman Tree
Node root = pq.peek();
// Traverse the Huffman tree and store the Huffman codes in a map
Map<Character, String> huffmanCode = new HashMap<>();
encode(root, "", huffmanCode);
// Print the Huffman codes
System.out.println("Huffman Codes are: " + huffmanCode);
System.out.println("The original string is: " + text);
// Print encoded string
StringBuilder sb = new StringBuilder();
for (char c: text.toCharArray()) {
sb.append(huffmanCode.get(c));
}
System.out.println("The encoded string is: " + sb);
System.out.print("The decoded string is: ");
if (isLeaf(root))
{
// Special case: For input like a, aa, aaa, etc.
while (root.freq-- > 0) {
System.out.print(root.ch);
}
}
else {
// Traverse the Huffman Tree again and this time,
// decode the encoded string
int index = -1;
while (index < sb.length() - 1) {
index = decode(root, index, sb);
}
}
}
// Huffman coding algorithm implementation in Java

54
public static void main(String[] args)
{
String text = "Huffman coding is a data compression algorithm.";
buildHuffmanTree(text);
}
}

OUTPUT:
Huffman Codes are: { =100, a=010, c=0011, d=11001, e=110000, f=0000, g=0001,
H=110001, h=110100,
i=1111, l=101010, m=0110, n=0111, .=10100, o=1110, p=110101, r=0010, s=1011, t=11011,
u=101011}
The original string is: Huffman coding is a data compression algorithm.
The encoded string
is:
110001101011000000000110010011110000111110110011111011100011001111101110001
010011001010
110110101000011111001101101010010110000101110111111111001111000101010100001
11100010111111
011110100011010100
The decoded string is: Huffman coding is a data compression algorithm.

RESULT:
Thus the java program to implement Huffman Coding was written, executed and
verified successfully.

55

You might also like