0% found this document useful (0 votes)
65 views65 pages

New Spanning Tree

The document describes programs to implement mergesort, quicksort, a binary search tree, and a red-black tree. It includes algorithms for each with steps like importing packages, creating classes, defining functions, and getting user input. Code snippets are provided for mergesort, quicksort, and a binary search tree that demonstrate inserting, deleting, searching, and traversing nodes. The results show the programs executed correctly and output was verified.

Uploaded by

Rekha G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views65 pages

New Spanning Tree

The document describes programs to implement mergesort, quicksort, a binary search tree, and a red-black tree. It includes algorithms for each with steps like importing packages, creating classes, defining functions, and getting user input. Code snippets are provided for mergesort, quicksort, and a binary search tree that demonstrate inserting, deleting, searching, and traversing nodes. The results show the programs executed correctly and output was verified.

Uploaded by

Rekha G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

EX.

NO: 1 IMPLEMENTATION OF MERGESORT AND QUICKSORT


DATE:

AIM :
To write the program for implementation of Mergesort and Quicksort-Analysis

ALGORITHM:

Step 1: Start the program.

Step 2: Import the necessary header files to get input by using array.

Step 3: Create a class as MergeSort and function as merge in that check the condition
if(list.length<=1) satisfies then return list.

Step 4: Declaration of function merge need to invoke and define by checking the loop with if
condition then print array copy.

Step 5: Create a main function as public static void main(String args[]) throws Exception.

Step 6: Introduce an object as Scanner scan = new Scanner( System.in ); and get an input through
BufferedReader.

Step 7: Print as “Enter number of integer elements” and “Elements after sorting”

Step 8: Sorting need to be carried out based on the rule of Merge sort and Quick sort.

Step 9: Stop the program.


PROGRAM CODING:(MERGE SORT)

package mergesort;
import java.util.Scanner;
public class MergeSort
{
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
sort(a, low, mid);
sort(a, mid, high);
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Merge Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
sort(arr, 0, n);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
OUTPUT:
Merge Sort Test

Enter number of integer elements


6

Enter 6 integer elements


98 24 31 12 45 76

Elements after sorting


12 24 31 45 76 98
PROGRAM CODING:(QUICK SORT)

package quicksort;
import java.util.Scanner;
public class QuickSort
{
public static void sort(int[] arr)
{
quickSort(arr, 0, arr.length - 1);
}
public static void quickSort(int arr[], int low, int high)
{
int i = low, j = high;
int temp;
int pivot = arr[(low + high) / 2];
while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if (low < j)
quickSort(arr, low, j);
if (i < high)
quickSort(arr, i, high);
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Quick Sort Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
sort(arr);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
OUTPUT:
Quick Sort Test

Enter number of integer elements


6

Enter 6 integer elements


98 24 31 12 45 76

Elements after sorting


12 24 31 45 76 98

RESULT:
Thus the program for the implementation of Mergesort and Quicksort has been
executed and output is verified.
EX.NO: 2 IMPLEMENTATION OF A BINARY SEARCH TREE
DATE:

AIM :
To write the program for implementation of a binary search tree.

ALGORITHM:

Step 1: Start the program.

Step 2: Import the necessary header files to get input by using array.

Step 3: Create a class as binary search tree.

Step 4: Declaration of function inorder,preorder,postorder..need to invoke and define by checking


the loop with if condition then print tree.

Step 5: Create a main function as public static void main(String args[]) throws Exception.

Step 6: Introduce an object as BST bst= new BST(); and get an input through BufferedReader.

Step 7: Print as “Binary Search Tree Test”and “Binary Search Tree Operations”.

Step 8: Stop the program.


PROGRAM CODING:
package binarysearchtree;
import java.util.Scanner;
import java.util.Scanner;
class BSTNode
{
BSTNode left, right;
int data;
public BSTNode()
{
left = null;
right = null;
data = 0;
}
public BSTNode(int n)
{
left = null;
right = null;
data = n;
}
public void setLeft(BSTNode n)
{
left = n;
}
public void setRight(BSTNode n)
{
right = n;
}
public BSTNode getLeft()
{
return left;
}
public BSTNode getRight()
{
return right;
}
public void setData(int d)
{
data = d;
}
public int getData()
{
return data;
}
}
class BST
{
private BSTNode root;
public BST()
{
root = null;
}
public boolean isEmpty()
{
return root == null;
}
public void insert(int data)
{
root = insert(root, data);
}
private BSTNode insert(BSTNode node, int data)
{
if (node == null)
node = new BSTNode(data);
else
{
if (data <= node.getData())
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
}
return node;
}
public void delete(int k)
{
if (isEmpty())
System.out.println("Tree Empty");
else if (search(k) == false)
System.out.println("Sorry "+ k +" is not present");
else
{
root = delete(root, k);
System.out.println(k+ " deleted from the tree");
}
}
private BSTNode delete(BSTNode root, int k)
{
BSTNode p, p2, n;
if (root.getData() == k)
{
BSTNode lt, rt;
lt = root.getLeft();
rt = root.getRight();
if (lt == null && rt == null)
return null;
else if (lt == null)
{
p = rt;
return p;
}
else if (rt == null)
{
p = lt;
return p;
}
else
{
p2 = rt;
p = rt;
while (p.getLeft() != null)
p = p.getLeft();
p.setLeft(lt);
return p2;
}
}
if (k < root.getData())
{
n = delete(root.getLeft(), k);
root.setLeft(n);
}
else
{
n = delete(root.getRight(), k);
root.setRight(n);
}
return root;
}
public int countNodes()
{
return countNodes(root);
}
private int countNodes(BSTNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
public boolean search(int val)
{
return search(root, val);
}
private boolean search(BSTNode r, int val)
{
boolean found = false;
while ((r != null) && !found)
{
int rval = r.getData();
if (val < rval)
r = r.getLeft();
else if (val > rval)
r = r.getRight();
else
{
found = true;
break;
}
found = search(r, val);
}
return found;
}
public void inorder()
{
inorder(root);
}
private void inorder(BSTNode r)
{
if (r != null)
{
inorder(r.getLeft());
System.out.print(r.getData() +" ");
inorder(r.getRight());
}
}
public void preorder()
{
preorder(root);
}
private void preorder(BSTNode r)
{
if (r != null)
{
System.out.print(r.getData() +" ");
preorder(r.getLeft());
preorder(r.getRight());
}
}
public void postorder()
{
postorder(root);
}
private void postorder(BSTNode r)
{
if (r != null)
{
postorder(r.getLeft());
postorder(r.getRight());
System.out.print(r.getData() +" ");
}
}
}
public class BinarySearchTree
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
BST bst = new BST();
System.out.println("Binary Search Tree Test\n");
char ch;
do
{
System.out.println("\nBinary Search Tree Operations\n");
System.out.println("1. insert ");
System.out.println("2. delete");
System.out.println("3. search");
System.out.println("4. count nodes");
System.out.println("5. check empty");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
bst.insert( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to delete");
bst.delete( scan.nextInt() );
break;
case 3 :
System.out.println("Enter integer element to search");
System.out.println("Search result : "+ bst.search( scan.nextInt() ));
break;
case 4 :
System.out.println("Nodes = "+ bst.countNodes());
break;
case 5 :
System.out.println("Empty status = "+ bst.isEmpty());
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
System.out.print("\nPost order : ");
bst.postorder();
System.out.print("\nPre order : ");
bst.preorder();
System.out.print("\nIn order : ");
bst.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:

Binary Search Tree Test


Binary Search Tree Operations
1. insert
2. delete
3. search
4. count nodes
5. check empty
5
Empty status = true
Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
y
Binary Search Tree Operations
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
3
Post order : 3
Pre order : 3
In order : 3
Do you want to continue (Type y or n)
y
Binary Search Tree Operations
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
2
Post order : 2 3
Pre order : 3 2
In order : 2 3
Do you want to continue (Type y or n)
y
Binary Search Tree Operations
1. insert
2. delete
3. search
4. count nodes
5. check empty
1
Enter integer element to insert
6
Post order : 2 6 3
Pre order : 3 2 6
In order : 2 3 6
Do you want to continue (Type y or n)
y
Binary Search Tree Operations
1. insert
2. delete
3. search
4. count nodes
5. check empty
2
Enter integer element to delete
3
3 deleted from the tree
Post order : 2 6
Pre order : 6 2
In order : 2 6
Do you want to continue (Type y or n)
y
Binary Search Tree Operations
1. insert
2. delete
3. search
4. count nodes
5. check empty
3
Enter integer element to search
6
Search result : true
Post order : 2 6
Pre order : 6 2
In order : 2 6
Do you want to continue (Type y or n)
y
Binary Search Tree Operations
1. insert
2. delete
3. search
4. count nodes
5. check empty
4
Nodes = 2
Post order : 2 6
Pre order : 6 2
In order : 2 6
Do you want to continue (Type y or n)
n

RESULT:
Thus the program for the implementation of a binary search tree has been executed and
output is verified.
EX.NO: 3 RED-BLACK TREE IMPLEMENTATION
DATE:

AIM :
To write the program for implementation of a red-black tree .

ALGORITHM:

Step 1: Start the program.

Step 2: Import the necessary header files to get input by using array.

Step 3: Create a class as RedBlackNode.

Step 4: Declaration of function inorder,preorder,postorder..need to invoke and define by checking


the loop with if condition then print tree.

Step 5: Create a main function as public static void main(String args[]) throws Exception.

Step 6: Introduce an object as RBTree rbt = new RBTree(Integer.MIN_VALUE);

and get an input through BufferedReader.

Step 7: Print as “Red Black Tree Test”and “Red Black Tree Operations”.

Step 8: Stop the program.


PROGRAM CODING:
package redblacktree;
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;
}
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 );
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)
{
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);
}
}
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);
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 :
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:

Red Black Tree Test


Red Black Tree Operations
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
5
Tree Cleared
Post order :
Pre order :
In order :
Do you want to continue (Type y or n)
y
Red Black Tree Operations
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
6
Post order : 6B
Pre order : 6B
In order : 6B
Do you want to continue (Type y or n)
y
Red Black Tree Operations
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
8
Post order : 8R 6B
Pre order : 6B 8R
In order : 6B 8R
Do you want to continue (Type y or n)
y
Red Black Tree Operations
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
1
Enter integer element to insert
2
Post order : 2R 8R 6B
Pre order : 6B 2R 8R
In order : 2R 6B 8R
Do you want to continue (Type y or n)
y
Red Black Tree Operations
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
2
Enter integer element to search
8
Search result : true
Post order : 2R 8R 6B
Pre order : 6B 2R 8R
In order : 2R 6B 8R
Do you want to continue (Type y or n)
y
Red Black Tree Operations
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
3
Nodes = 3
Post order : 2R 8R 6B
Pre order : 6B 2R 8R
In order : 2R 6B 8R
Do you want to continue (Type y or n)
y
Red Black Tree Operations
1. insert
2. search
3. count nodes
4. check empty
5. clear tree
4
Empty status = false
Post order : 2R 8R 6B
Pre order : 6B 2R 8R
In order : 2R 6B 8R
Do you want to continue (Type y or n)
n

RESULT:
Thus the program for the implementation of red-black tree has been executed and
output is verified.
EX.NO: 4 HEAP IMPLEMENTATION
DATE:

AIM:
To write a program for heap implementation.

ALGORITHM:

Step 1: Start the program.

Step 2: Import the necessary header files to get input by using array.

Step 3: Create a class heap implimentation function in that check the condition
satisfies the list.

Step 4: Declaration of heap function need to invoke and define by checking the loop with if
condition then print array copy.

Step 5: Create a main function as public static void main(String args[]) throws Exception.

Step 6: Print as “Please enter the list of elements,one element per line”and “write 'STOP' when
list is completed”

Step 7: Stop the program.


PROGRAM CODING:
public class MinHeap
{
private int[] Heap;
private int size;
private int maxsize;

private static final int FRONT = 1;

public MinHeap(int maxsize)


{
this.maxsize = maxsize;
this.size = 0;
Heap = new int[this.maxsize + 1];
Heap[0] = Integer.MIN_VALUE;
}

private int parent(int pos)


{
return pos / 2;
}

private int leftChild(int pos)


{
return (2 * pos);
}
private int rightChild(int pos)
{
return (2 * pos) + 1;
}
private boolean isLeaf(int pos)
{
if (pos >= (size / 2) && pos <= size)
{
return true;
}
return false;
}
private void swap(int fpos, int spos)
{
int tmp;
tmp = Heap[fpos];
Heap[fpos] = Heap[spos];
Heap[spos] = tmp;
}
private void minHeapify(int pos)
{
if (!isLeaf(pos))
{
if ( Heap[pos] > Heap[leftChild(pos)] || Heap[pos] > Heap[rightChild(pos)])
{
if (Heap[leftChild(pos)] < Heap[rightChild(pos)])
{
swap(pos, leftChild(pos));
minHeapify(leftChild(pos));
}else
{
swap(pos, rightChild(pos));
minHeapify(rightChild(pos));
}
}
}
}
public void insert(int element)
{
Heap[++size] = element;
int current = size;
while (Heap[current] < Heap[parent(current)])
{
swap(current,parent(current));
current = parent(current);
}
}

public void print()


{
for (int i = 1; i <= size / 2; i++ )
{
System.out.print(" PARENT : " + Heap[i] + " LEFT CHILD : " + Heap[2*i]
+ " RIGHT CHILD :" + Heap[2 * i + 1]);
System.out.println();
}
}
public void minHeap()
{
for (int pos = (size / 2); pos >= 1 ; pos--)
{
minHeapify(pos);
}
}
public int remove()
{
int popped = Heap[FRONT];
Heap[FRONT] = Heap[size--];
minHeapify(FRONT);
return popped;
}
public static void main(String...arg)
{
System.out.println("The Min Heap is ");
MinHeap minHeap = new MinHeap(15);
minHeap.insert(5);
minHeap.insert(3);
minHeap.insert(17);
minHeap.insert(10);
minHeap.insert(84);
minHeap.insert(19);
minHeap.insert(6);
minHeap.insert(22);
minHeap.insert(9);
minHeap.minHeap();
minHeap.print();
System.out.println("The Min val is " + minHeap.remove());
}
}
OUTPUT:
The Min Heap is
PARENT : 3 LEFT CHILD : 5 RIGHT CHILD :6
PARENT : 5 LEFT CHILD : 9 RIGHT CHILD :84
PARENT : 6 LEFT CHILD : 19 RIGHT CHILD :17
PARENT : 9 LEFT CHILD : 22 RIGHT CHILD :10
The Min val is 3

RESULT: Thus the program for heap implementation has been executed and output is verified.
EX.NO: 5 FIBONACCI HEAP IMPLEMENTATION
DATE:

AIM:
To write a program for the fibonacci heap implementation.

ALGORITHM:

Step 1: Start the program.

Step 2: Import the necessary header files to get input by using array.

Step 3: Create a class as Fibonacci.

Step 4: Create a main function as public static void main(String args[]) throws Exception.

Step 5: Introduce an object and get an input through BufferedReader.

Step 6: Print as “Please enter the list of elements,one element per line”and “write 'STOP' when
list is completed”

Step 7: Stop the program.


PROGRAM CODING:
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)
{
node.left = root;
node.right = root.right;
root.right = node;
node.right.left = node;
if (element < root.element)
root = node;
}
else
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;
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 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
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 program for the fibonacci heap implementation has been executed and output
is verified.
EX.NO: 6 GRAPH TRAVERSALS
DATE:

AIM:
To write a program for the implementation of graph traversals

ALGORITHM:

Step 1: Start the program.

Step 2: Import the necessary header files to get input by using array.

Step 3: Create a main class .

Step 4: Create a main function as public static void main(String args[]) throws Exception.

Step 5: Introduce an object and get an input through BufferedReader.

Step 6: Print as “Please enter the list of elements,one element per line”and “write 'STOP' when
list is completed”

Step 7: Stop the program.


PROGRAM CODING:
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++;
}
stack.pop();
}
}
public static void main(String...arg)
{
int number_of_nodes, source;
Scanner scanner = null;
try
{
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
0101
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 program for the implementation of graph traversals has been executed and
output is verified.
EX.NO: 7 SPANNING TREE IMPLEMENTATION
DATE:

AIM:
To write a program for the implementation of spanning tree.\

ALGORITHM:

Step 1: Start the program.

Step 2: Import the necessary header files to get input by using array.

Step 3: Create a class spanning tree function in that check the condition
satisfies the list.

Step 4: Declaration of function prims need to invoke and define by checking the loop with if
condition then print array copy.

Step 5: Create a main function as public static void main(String args[]) throws Exception.

Step 6: Print as “Please enter the list of elements,one element per line”and “write 'STOP' when
list is completed”

Step 7: Sorting need to be carried out based on the rule of prims algorithm.

Step 8: Stop the program.


PROGRAM CODING:
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)


{
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 + 1];
}

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())
{
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;
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 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] = 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);

System.out.println("The Shorted Path to all nodes are ");


for (int i = 1; i <= dijkstrasAlgorithm.distances.length - 1; i++)
{
System.out.println(source + " to " + i + " is "+ dijkstrasAlgorithm.distances[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
OUTPUT:
Enter the number of vertices
5
Enter the Weighted Matrix for the graph
09653
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 program for the implementation of spanning tree has been executed and
output is verified.
EX.NO: 8 SHORTEST PATH ALGORITHM (DIJIKSTRA’S
ALGORITHM,BELLMAN FORD ALGORITHM)
DATE:

AIM:
To write a program for the implementation of shortest path algorithm (dijikstra’s
algorithm,bellman ford algorithm)

ALGORITHM:

Step 1: Start the program.

Step 2: Import the necessary header files to get input by using array.

Step 3: Create a class as dijikstra’s algorithm and bellman ford algorithm.

Step 4: Declaration of function merge need to invoke and define by checking the loop with if
condition then print array copy.

Step 5: Create a main function as public static void main(String args[]) throws Exception.

Step 6: Introduce an object and get an input through BufferedReader.

Step 7: Print as “Please enter the list of elements,one element per line”and “write 'STOP' when
list is completed”

Step 8: Sorting need to be carried out based on the rule of shortest path algorithm.

Step 9: Stop the program.


PROGRAM CODING:( DIJIKSTRA’S ALGORITHM)
package com.hinguapps.graph;

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 destination,


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++)
{
if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)
{
if (distances[destinationnode] > distances[sourcenode]
+ adjacencymatrix[sourcenode][destinationnode])
distances[destinationnode] = distances[sourcenode]
+ adjacencymatrix[sourcenode][destinationnode];
}
}
}
}
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)
{
if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)
{
if (distances[destinationnode] > distances[sourcenode]
+ adjacencymatrix[sourcenode][destinationnode])
System.out
.println("The Graph contains negative egde cycle");
}
}
}
for (int vertex = 1; vertex <= numberofvertices; vertex++)
{
if (vertex == destination)
System.out.println("distance of source " + source + " to "
+ vertex + " is " + distances[vertex]);
}
}
public static void main(String... arg)
{
int numberofvertices = 0;
int source, destination;
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();
System.out.println("Enter the destination vertex: ");
destination = scanner.nextInt();
BellmanFord bellmanford = new BellmanFord(numberofvertices);
bellmanford.BellmanFordEvaluation(source, destination, adjacencymatrix);
scanner.close();
}
}
OUTPUT:
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 the source vertex
1
Enter the destination vertex:
4
distance of source 1 to 4 is -6

PROGRAM CODING: (BELLMANN FORD ALGORITHM)


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++)
{
if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)
{
if (distances[destinationnode] > distances[sourcenode]
+ adjacencymatrix[sourcenode][destinationnode])
distances[destinationnode] = distances[sourcenode]
+ adjacencymatrix[sourcenode][destinationnode];
}}}}

for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)


{
for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)
{
if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)
{
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();
BellmanFord bellmanford = new BellmanFord(numberofvertices);
bellmanford.BellmanFordEvaluation(source, adjacencymatrix);
scanner.close();
}
}
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 the source vertex


1

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 program for the implementation of shortest path algorithm (dijikstra’s
algorithm,bellman ford algorithm) has been executed and output is verified.
EX.NO: 9 IMPLEMENTATION OF MATRIX CHAIN MULTIPLICATION
DATE:

AIM:
To write a program for the implementation of matrix chain multiplication

ALGORITHM:

Step 1: Start the program.

Step 2: Import the necessary header files to get input by using array.

Step 3: Create a class matrix chain multiplication

Step 4: Declaration of function need to invoke and define by checking the loop with if condition
then print array copy.

Step 5: Create a main function as public static void main(String args[]) throws Exception.

Step 6: Print as “Please enter the list of elements,one element per line”and “write 'STOP' when
list is completed”

Step 7: Stop the program.


PROGRAM CODING:

import java.util.Scanner;
public class OptimalParanthesizationUsingDP
{
private int[][] m;
private int[][] s;
private int n;

public OptimalParanthesizationUsingDP(int[] p)
{
n = p.length - 1;
m = new int[n + 1][n + 1];
s = new int[n + 1][n + 1];
matrixChainOrder(p);
}

private void matrixChainOrder(int[] p)


{
.
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])
{
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 p[i]
Enter the total length:
5
Enter the dimensions:
24521
Matrices are of order:
A1-->2x4
A2-->4x5
A3-->5x2
A4-->2x1
(A[1](A[2](A[3]A[4])))

RESULT: Thus the program for the implementation of matrix chain multiplication has been
executed and output is verified.
EX.NO: 10 Activity Selection and Huffman Coding Implementation.
DATE:

AIM:
To write a program for the implementation of Huffman coding.

ALGORITHM:

Step 1: Start the program.

Step 2: Import the necessary header files to get input by using array.

Step 3: Create a class for huffmann code

Step 4: Declaration of function need to invoke and define by checking the loop with if condition
then print array copy.

Step 5: Create a main function as public static void main(String args[]) throws Exception.

Step 6: Print as “Please enter the list of elements,one element per line”and “write 'STOP' when
list is completed”

Step 7: Stop the program.


PROGRAM CODING:

import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Comparator;

class HuffmanNode
{
int data;
char c;
HuffmanNode left;
HuffmanNode right;
}
class MyComparator implements Comparator<HuffmanNode> {
public int compare(HuffmanNode x, HuffmanNode y)
{
return x.data - y.data;
}
}
public class Huffman
{
public static void printCode(HuffmanNode root, String s)
{
if (root.left == null&& root.right == null&& Character.isLetter(root.c))
{
System.out.println(root.c + ":" + s);
return;
}
printCode(root.left, s + "0");
printCode(root.right, s + "1");
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int n = 6;
char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' };
int[] charfreq = { 5, 9, 12, 13, 16, 45 };
PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new
MyComparator());
for (int i = 0; i < n; i++)
{
HuffmanNode hn = new HuffmanNode();
hn.c = charArray[i];
hn.data = charfreq[i];
hn.left = null;
hn.right = null;
q.add(hn);
}
HuffmanNode root = null;
while (q.size() > 1) {
HuffmanNode x = q.peek();
q.poll();
HuffmanNode y = q.peek();
q.poll();
HuffmanNode f = new HuffmanNode();
f.data = x.data + y.data;
f.c = '-';
f.left = x;
f.right = y;
root = f;
q.add(f);
}
printCode(root, "");
}
}
Output:
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111

RESULT: Thus the program for the activity selection and huffman coding implementation.

has been executed and output is verified.

You might also like