0% found this document useful (0 votes)
103 views77 pages

ADSA Lab Record (CP 4161)

lab

Uploaded by

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

ADSA Lab Record (CP 4161)

lab

Uploaded by

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

Ex no: 1 IMPLEMENTATION OF RECURSIVE FUNCTION FOR

TREE TRAVERSAL AND FIBONACCI.

Aim:

To create a java program for the implementation of recursive function for tree
traversal and Fibonacci.

Algorithm:

1. Start the program

2. Design the first thread that generates a random integer for every 1 second .

3. If the first thread value is even, design the second thread as the square of the number
and then print it.

4.If the first thread value is odd, then third thread will print the value of cube of
the number.

5. Stop the program.

PROGRAM CODING :

class RandomGen Thread implements Runnable

double mun;

public void run()

try

SquareThread sqt = new SquareThread();

Thread squamThread = new Thread(sqt); CubeThread cbt = new CubeThread();

Thread cubeThread = new Thread(cbt); squareThread.start();

cubeThread.start();

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

System.out.println(“t1-”+i);

if(i%2==0)

sqt.setNum(new Double(i));

else

cbt. setNum(new Double(i));

Thread. sleep(1000);

catch(InterruptedException e)

e.printStackTrace();

class SquareThread implements Runnable

Double num;

public void run()

try

int i=0;
do{

i++;

if(num != null&&num %2 ==0)

System.out.println(“t2->square of “+num+”=”+(num*num));

num = null;

Thread.sleep(1000);

}while(i<=5);

catch (Exception e)

e.printStackTrace();

public Double getNum()

return num;

public void setNum(Double num)

this.num = num;

class CubeThread implements Runnable

Double num;
public void run()

try {

int i=0;

do{

i++;

if(num != null&&num%2 !=0)

System.out.println(“t3-->Cube of “+num+”=”+(num*num*num));

num=null;

Thread.sleep(1000);

while(i<=5);

catch (Exception e)

e.printStackTrace();

Public Double getNum()

return num;

public void setNum(Double mum)

this.num = num;
}

public class Main

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

Thread randomThread = new Thread(new RandomGenThread()); randomThread.start();

OUTPUT :

Enter the number : 10


The fibonacci series : 0 1 1 2 3 5 8 13 21 34

Result :
Thus the program for the implementation of recursive function for tree traversal and
Fibonacci is created and the output is verified successfully.
Ex no: 2 IMPLEMENTATION OF ITERATIVE FUNCTION FOR TREE
TRAVERSAL AND FIBONACCI.

Aim:

To create a java program for the implementation of iterative function for tree traversal
and Fibonacci.

Algorithm:

1. Start the program

2. Design the first thread that generates a random integer for every 1 second .

3. If the first thread value is even, design the second thread as the square of the number
and then print it.

4. If the first thread value is odd, then third thread will print the value of cube of
the number.

5. Stop the program.

PROGRAM CODING:

import java.io.*;

public class FileInfo

public static void main(String[] args)throws10Exception

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print(“\nEnter A File Name:”);

String fName = br.readLine();

File f = new File(fName);

String result = f.exists() ? “exists.” : “does not exist”;

System.out.println(“\nThe given file “ + result);


if(f.exists())

System.out.println(“The given file is “ + result);

System.out.println(“The given file is “ + result);

System.out.println(“The given file length is “ + f.length() + “ in bytes”);

if (fName.endsWith(“.jpg”) || fName.endsWith(“.gif”) || fName.endsWith(".png” )

System.out.println(“The given file is an image file");

else if (fName.endsWith(“.exe"))

System.out.println("The given file is an image file. ");

else if(fName.ends With(".exe))

System. out. println(“The given file is an executable file.");

else if(fName.endsWith(".txt"))

System.out.println(“The given file is a text file.”);

else

System.out.println(“The file type is unknown.”);

}
}

OUTPUT :
Result :

Thus the program for the implementation of iterative function for tree traversal and
Fibonacci is created and the output is verified successfully.

Ex no:3(a) Implementation of Merge Sort Analysis

AIM:

To write a java program for the implementation of merge sort.

ALGORITHM:
1. If the list has only one element, return the list and terminate.
2. Split the list into two halves that are as equal in length as possible
3. Using recursion, sort both lists using merge sort.
4. Merge the two sorted lists and return the result.
5. Stop the program.

PROGRAM CODING:

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();
}
}
Result:
Thus the program for the implementation of Merge sort is created and the output is
verified successfully.

Ex no:3(b) IMPLEMENTATION OF QUICK SORT

AIM:

To write a java program for the implementation of quick sort.

ALGORTIHM:

1. Choose an element, called pivot, from the list. Generally pivot can be the middle index

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

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

}
Result:

Thus the program for the implementation of Quick sort is created and the output is
verified successfully.
Ex no:4 IMPLEMENTATION OF BINARY SEARCH TREE

AIM:

To write a java program for the implementation of 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

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

9. If we reach to a leaf node and it is also not matching, then display "Element not found" and
terminate the function.

PROGRAM CODING:

public class BinarySearchTree

public static Node root;

public BinarySearchTree()

this.root = null;

public boolean find(int id)


{

Node current = root;

while(current!=null)

if(current.data==id)

return true;

else if(current.data>id)

current = current.left;

Else

current = current.right;

return false;

public boolean delete(int id)

Node parent = root;

Node current = root;

boolean isLeftChild = false;

while(current.data!=id)

parent = current;

if(current.data>id)
{

isLeftChild = true;

current = current.left;

Else

isLeftChild = false;

current = current.right;

if(current ==null)

return false;

//if i am here that means we have found the node

//Case 1: if node to be deleted has no children

if(current.left==null && current.right==null)

if(current==root)

root = null;

if(isLeftChild ==true)

parent.left = null;

Else

{
parent.right = null;

//Case 2 : if node to be deleted has only one child

else if(current.right==null)

if(current==root)

root = current.left;

else if(isLeftChild)

parent.left = current.left;

Else

parent.right = current.left;

else if(current.left==null)

if(current==root)

root = current.right;

else if(isLeftChild)

parent.left = current.right;
}

Else

parent.right = current.right;

else if(current.left!=null && current.right!=null)

//now we have found the minimum element in the right sub tree

Node successor = getSuccessor(current);

if(current==root)

root = successor;

else if(isLeftChild)

parent.left = successor;

Else

parent.right = successor;

successor.left = current.left;

return true;

public Node getSuccessor(Node deleleNode)


{

Node successsor =null;

Node successsorParent =null;

Node current = deleleNode.right;

while(current!=null)

successsorParent = successsor;

successsor = current;

current = current.left;

//check if successor has the right child, it cannot have left child for sure

// if it does have the right child, add it to the left of successorParent.

// successsorParent

if(successsor!=deleleNode.right)

successsorParent.left = successsor.right;

successsor.right = deleleNode.right;

return successsor;

public void insert(int id)

Node newNode = new Node(id);

if(root==null)

root = newNode;

return;

}
Node current = root;

Node parent = null;

while(true)

parent = current;

if(id<current.data)

current = current.left;

if(current==null)

parent.left = newNode;

return;

Else

current = current.right;

if(current==null)

parent.right = newNode;

return;

public void display(Node root)

if(root!=null)
{

display(root.left);

System.out.print(" " + root.data);

display(root.right);

public static void main(String arg[])

BinarySearchTree b = new BinarySearchTree();

b.insert(3);b.insert(8);

b.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);

b.insert(20);b.insert(25);b.insert(15);b.insert(16);

System.out.println("Original Tree : ");

b.display(b.root);

System.out.println("");

System.out.println("Check whether Node with value 4 exists : " + b.find(4));

System.out.println("Delete Node with no children (2) : " + b.delete(2));

b.display(root);

System.out.println("\n Delete Node with one child (4) : " + b.delete(4));

b.display(root);

System.out.println("\n Delete Node with Two children (10) : " + b.delete(10));

b.display(root);

class Node

int data;
Node left;

Node right;

public Node(int data)

this.data = data;

left = null;

right = null;

}
OUTPUT

Result:

Thus the program for the implementation of binary search tree is created and the
output is verified successfully.
Ex no: 5 RED-BLACK TREE IMPLEMENTATION

AIM:

To write a java program for the implementation of Red-Black Tree.

ALGORITHM:

1. Check whether tree is Empty.

2. If tree is Empty then insert the new Node as Root node with colour Black and exit from the
operation.

3. If tree is not Empty then insert the new Node as a leaf node with Red colour.

4. If the parent of new Node is Black then exit from the operation.

5. If the parent of new Node is Red then check the colour of parent node's sibling of new Node.

6. If it is Black or NULL node then make a suitable Rotation and Recolor it.

7. If it is Red colour node then perform Recolor and Recheck it. Repeat the same until tree becomes
Red Black Tree.

PROGRAM CODING:

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

/* 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 :

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 :

Result:

Thus the program for the implementation of Red black tree is created and the output is
verified successfully.
Ex no:6 HEAP IMPLEMENTATION

AIM:

To write a java program for the implementation of Heap.

ALGORITHM:

1.Call the build Max Heap() 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 shift Down() 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 build Max Heap() operation is run once, and is O(n) in performance. the shift Down()
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 CODING :

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];

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

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:

Result:

Thus the program for the implementation of Heap is created and the output is verified
successfully.
Ex no:7 FIBONACCI HEAP IMPLEMENTATION
AIM:

To write a java program for the implementation of Fibonacci Heap.

ALGORITHM:

1. Call the build Min Heap() 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. Extract Min() deletes the node with minimum key from the heap.
5. Union(H) merge heap H and create a new one.
6. Decrease Key(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 CODING :

importjava.util.*;
classFibonacciHeapNode
{
FibonacciHeapNode child, left, right, parent;
int element;
publicFibonacciHeapNode(int element)
{
this.right = this;
this.left = this;
this.element = element;
}
}
classFibonacciHeap
{
privateFibonacciHeapNode root;
privateint count;
publicFibonacciHeap()
{
root = null;
count = 0;
}
publicbooleanisEmpty()
{
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 = ");
FibonacciHeapNodeptr = 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");
FibonacciHeapfh = new FibonacciHeap();
charch;
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:

Result:
Thus the program for the implementation of Fibonacci heap implementation is created
and the output is verified successfully.

Ex no:8 GRAPH TRAVERSALS

AIM:

To write a java program to implement Graph Traversals using Depth First Search tree algorithm.

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

package org.arpit.java2blog;

import java.util.ArrayList;

import java.util.List;

import java.util.Stack;

public class DepthFirstSearchExampleNeighbourList

static class Node

int data;

boolean visited;

List<Node> neighbours;

Node(int data)

{
this.data=data;

this.neighbours=new ArrayList<>();

public void addneighbours(Node neighbourNode)

this.neighbours.add(neighbourNode);

public List<Node> getNeighbours()

return neighbours;

public void setNeighbours(List<Node> neighbours)

this.neighbours = neighbours;

// Recursive DFS

public void dfs(Node node)

System.out.print(node.data + " ");

List<Node> neighbours=node.getNeighbours();

for (int i = 0; i < neighbours.size(); i++)

Node n=neighbours.get(i);

if(n!=null && !n.visited)

dfs(n);

n.visited=true;
}

// Iterative DFS using stack

public void dfsUsingStack(Node node)

Stack<Node> stack=new Stack<Node>();

stack.add(node);

node.visited=true;

while (!stack.isEmpty())

Node element=stack.pop();

System.out.print(element.data + " ");

List<Node> neighbours=element.getNeighbours();

for (int i = 0; i < neighbours.size(); i++)

Node n=neighbours.get(i);

if(n!=null && !n.visited)

stack.add(n);

n.visited=true;

public static void main(String arg[])

Node node40 =new Node(40);


Node node10 =new Node(10);

Node node20 =new Node(20);

Node node30 =new Node(30);

Node node60 =new Node(60);

Node node50 =new Node(50);

Node node70 =new Node(70);

node40.addneighbours(node10);

node40.addneighbours(node20);

node10.addneighbours(node30);

node20.addneighbours(node10);

node20.addneighbours(node30);

node20.addneighbours(node60);

node20.addneighbours(node50);

node30.addneighbours(node60);

node60.addneighbours(node70);

node50.addneighbours(node70);

DepthFirstSearchExampleNeighbourList dfsExample = new


DepthFirstSearchExampleNeighbourList();

System.out.println("The DFS traversal of the graph using stack ");

dfsExample.dfsUsingStack(node40);

System.out.println();

// Resetting the visited flag for nodes

node40.visited=false;

node10.visited=false;

node20.visited=false;

node30.visited=false;

node60.visited=false;

node50.visited=false;

node70.visited=false;
System.out.println("The DFS traversal of the graph using recursion ");

dfsExample.dfs(node40);

OUTPUT :

Result:
Thus the program for the implementation of Graph traversal heap implementation is
created and the output is verified successfully.

Ex no: 9 SPANNING TREE IMPLEMENTATION

AIM:

To write a java program for the implementation of Spanning Tree.

ALGORITHM:

1. Create a graph F (a set of trees), where each vertex in the graph is a separate tree.

2. Step:create a set S containing all the edges in the graph.

3. While S is nonempty and F is not yet spanning.

4. Remove an edge with minimum weight from S.

5. If the removed edge connects two different trees then add it to the forest F, combining two treess
into a single tree.

PROGRAM CODING:

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)

this.numberOfVertices = numberOfVertices;

edges = new LinkedList<Edge>();

visited = new int[this.numberOfVertices + 1];

spanning_tree = new int[numberOfVertices + 1][numberOfVertices + 1];

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 != destination)

Edge edge = new Edge();

edge.sourcevertex = source;

edge.destinationvertex = destination;

edge.weight = adjacencyMatrix[source][destination];

adjacencyMatrix[destination][source] = MAX_VALUE;

edges.add(edge);

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++)

System.out.print(spanning_tree[source][destination] + "\t");

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];

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;

adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];

for (int sourcevertex = 1; sourcevertex <= number_of_nodes; sourcevertex++)

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;

if (adjacencyMatrix[element][i] >= 1 && visited[i] == 0)

stack.push(i);

visited[i] = 1;

adjacencyMatrix[element][i] = 0;// mark as labelled;

adjacencyMatrix[i][element] = 0;

element = i;

i = 1;

continue;

i++;

}
stack.pop();

return cyclepresent;

Result:
Thus the program for the implementation of spanning tree is created and the output is
verified successfully.

Ex no:10(a) DIJKSTRAS ALGORITHM


AIM:

To write a java program for the implementation of Dijkstra’s Algorithm Using Shortest Path.

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
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.

Repeating of steps 4 to 7 until there aren't any nodes left with a permanent distance, which neighbours
still have temporary distance

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

}
Result:
Thus the program for the implementation of Dijkstra’s algorithm is created and the
output is verified successfully.

Ex no:10(b) BELLMAN FORD ALGORITHM

AIM:

To write a java program for the implementation of Bellman Ford Algorithm by using the concept
Shortest Path.

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 read
justed 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 CODING:

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:

Result:
Thus the program for the implementation of Bellman ford is created and the output is
verified successfully.
Ex no:11 IMPLEMENTATION OF MATRIX CHAIN MULTIPLICATION

AIM :

To write a java program for the implementation of 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
parethesization.
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)
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 CODING :

public class Matrix Chain Multi


{
void matrix chain(int a[])
{
int q;
int n=a.length;
int m[][]=new int[n][n];
int s[][]=new int[n][n];
for (int i=1;i<n;i++)
m[i][i]=0;
for (int l=2;l<n;l++) //l is the length
{
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-1;k++)
{
q=m[i][k]+m[k+1][j]+a[i-1]*a[k]*a[j];
if(q<m[i][j])
{
m[i][j]=q;
s[i][j]=k;
}
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
System.out.print(m[i][j]+" ");
System.out.println();
}
print_optimal(s,1,6);
}
void print_optimal(int s[][],int i,int j)
{
if (i==j)
System.out.print("A"+i);
else
{
System.out.print("(");
print_optimal(s,i,s[i][j]);
print_optimal(s,s[i][j]+1,j);
System.out.print(")");
}
}
public static void main(String args[])
{
int a[]={30, 35, 15, 5, 10, 20, 25};//A1:-30x35, A2:- 35x15, A3:- 15x5, A4:- 5x10 , A5:- 10x20, A6:-
20x25
MatrixChainMulti n=new MatrixChainMulti();
n.matrixchain(a);
}
}
Result:
Thus the program for the implementation of Matrix chain multiplication is created
and the output is verified successfully.

Ex no:12 IMPLEMENTATION OF HUFFMAN CODING.

AIM:

To write a java program for the implementation of 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 CODING :

import java.util.*;

abstract class HuffmanTree implements Comparable<HuffmanTree>

public final int frequency;

public HuffmanTree(int freq)

frequency = freq;
}

public int compareTo(HuffmanTree tree)

return frequency - tree.frequency;

class HuffmanLeaf extends HuffmanTree

public final char value;

public HuffmanLeaf(int freq, char val)

super(freq);

value = val;

class HuffmanNode extends HuffmanTree

public final HuffmanTree left, right;

public HuffmanNode(HuffmanTree l, HuffmanTree r)

super(l.frequency + r.frequency);

left = l;

right = r;

public class HuffmanCode

public static HuffmanTree buildTree(int[] charFreqs)


{

PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>();

for (int i = 0; i < charFreqs.length; i++)

if (charFreqs[i] > 0)

trees.offer(new HuffmanLeaf(charFreqs[i], (char)i));

assert trees.size() > 0;

while (trees.size() > 1)

HuffmanTree a = trees.poll();

HuffmanTree b = trees.poll();

trees.offer(new HuffmanNode(a, b));

return trees.poll();

public static void printCodes(HuffmanTree tree, StringBuffer prefix)

assert tree != null;

if (tree instanceof HuffmanLeaf)

HuffmanLeaf leaf = (HuffmanLeaf)tree;

System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix);

} else if (tree instanceof HuffmanNode)

HuffmanNode node = (HuffmanNode)tree;

prefix.append('0');

printCodes(node.left, prefix);

prefix.deleteCharAt(prefix.length()-1);

prefix.append('1');
printCodes(node.right, prefix);

prefix.deleteCharAt(prefix.length()-1);

public static void main(String[] args)

String test = "this is an example for huffman encoding";

int[] charFreqs = new int[256];

for (char c : test.toCharArray())

charFreqs[c]++;

HuffmanTree tree = buildTree(charFreqs);

System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE");

printCodes(tree, new StringBuffer());

}
OUTPUT:

Result:
Thus the program for the implementation of Huffman coding is created and the output
is verified successfully.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy