Data structure lab programs
Data structure lab programs
PAGE
S.NO DATE NAME OF THE EXPERIMENT SIGN
NO
14 IMPLEMENT A KRUSKAL’S
ALGORITHM
AIM
To write a Java program to implement using java generic class, the stack.
ALGORITHM
importjava.util.*;
class stack
{
static final int max=1000;
int top;
int a[]=new int[max];
booleanisEmpty()
{
return(top<0);
}
stack()
{
top=-1;
}
boolean push(int x)
{
if(top>=max-1)
{
System.out.println("stack overflow");
return false;
}
else
{
a[++top]=x;
System.out.println(x+"pushed into stack");
return true;
}
}
int pop()
{
if(top<0)
{
System.out.println("stack underflow");
return 0;
}
else
{
int x=a[top--];
return x;
}
}
int peek()
{
if(top<0)
{
System.out.println("stack underflow");
return 0;
}
else
{
int x=a[top];
return x;
}
}
void print()
{
for(int i=top;i>-1;i--)
{
System.out.println(" "+a[i]);
}
}
public static void main(String args[])
{
stack s=new stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop()+"popped from stack");
System.out.println("top element is:"+s.peek());
System.out.println("element present in stack:");
s.print();
}
}
Output:
AIM
To write a program that implement the quick sort method.
ALGORITHM
Step 2: An array is divided into sub arrays by selecting the pivot element
Step 3: While dividing the array pivot element should be position is such a way
that element less than pivot (or) keep on the left side and elements than
better pivot or on the right side of the pivot
Step 4: The left and right some arrays or also divided using the same approach
this process continue until such sub array a contains single element
Step 5: This is at the point array element are already sorted finally element or
combined the formula sorted
Step 6: Stop the program
2.Quick Sort
PROGRAM:
import java.io.*;
class quicksort
{
int partition(intarr[],intlow,int high)
{
int pivot=arr[high];
int i=(low-1);
for(int j=low;j<high;j++)
{
if(arr[j]<=pivot)
{
i++;
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
int temp=arr[i+1];
arr[i+1]=arr[high];
arr[high]=temp;
return i+1;
}
void sort(intarr[],intlow,int high)
{
if(low<high)
{
int pi=partition(arr,low,high);
sort(arr,low,pi-1);
sort(arr,pi+1,high);
}
}
static void printarray(intarr[])
{
int n=arr.length;
for(int i=0;i<n;i++)
System.out.println(arr[i]+"");
System.out.println();
}
public static void main(String args[])
{
int[]arr={10,7,8,9,1,5};
int n=arr.length;
quicksortob=new quicksort();
ob.sort(arr,0,n-1);
System.out.println("sorted array:");
printarray(arr);
}
}
Output:
sorted array:
1
5
7
8
9
10
EXP. NO.3
DATE:
IMPLEMENT THE MERGE SORT METHOD
AIM
To write a Java program to implement the merge sort method.
ALGORITHM
classMergeSort
{
void merge(intarr[],intl,intm,int r)
{
int n1=m-l+1;
int n2=r-m;
int L[]=new int[n1];
int R[]=new int[n2];
for(int i=0;i<n1;++i)
L[i]=arr[l+i];
for(int j=0;j<n2;++j)
R[j]=arr[m+1+j];
int i=0,j =0;
int k=l;
while(i<n1&&j<n2)
{
if(L[i]<=R[j])
{
arr[k]=L[i];
i++;
}
else
{
arr[k]=R[j];
j++;
}
k++;
}
while(i<n1)
{
arr[k]=L[i];
i++;
k++;
}
while(j<n2)
{
arr[k]=R[j];
j++;
k++;
}
}
void sort(intarr[],intl,int r)
{
if(l<r)
{
int m=l+(r-l)/2;
sort(arr,l,m);
sort(arr,m+1,r);
merge(arr,l,m,r);
}
}
static void printArray(intarr[])
{
int n=arr.length;
for(int i=0;i<n;++i)
System.out.println(arr[i]+" ");
System.out.println();
}
public static void main(String args[])
{
intarr[]={12,11,13,5,6,7};
System.out.println("Given Array");
printArray(arr);
MergeSortob=new MergeSort();
ob.sort(arr,0,arr.length-1);
System.out.println("\nSorted array");
printArray(arr);
}
}
Output:
Given Array:
12
11
13
5
6
7
Sorted array:
5
6
7
11
12
13
EXP. NO.4
DATE:
FUNCTIONS TO CREATING A SPLAYTREE
AIM
To write a Java program to implement for function to create a splay tree.
ALGORITHM
class Tree
{
static class node
{
int key;
node left, right;
};
static node TreeNode(int key)
{
nodeNode = new node();
Node.key = key;
Node.left = Node.right = null;
return (Node);
}
static node rightRotate(node x)
{
node y = x.left;
x.left = y.right;
y.right = x;
return y;
}
static node leftRotate(node x)
{
node y = x.right;
x.right = y.left;
y.left = x;
return y;
}
static node splay(node root, int key)
{
if (root == null || root.key == key)
return root;
if (root.key> key)
{
if (root.left == null) return root;
if (root.left.key> key)
{
root.left.left = splay(root.left.left, key);
root = rightRotate(root);
}
else if (root.left.key< key)
{
root.left.right = splay(root.left.right, key);
if (root.left.right != null)
root.left = leftRotate(root.left);
}
return (root.left == null) ? root :rightRotate(root);
}
else
{
if (root.right == null) return root;
if (root.right.key> key)
{
root.right.left = splay(root.right.left, key);
if (root.right.left != null)
root.right = rightRotate(root.right);
}
else if (root.right.key< key)
{
root.right.right = splay(root.right.right, key);
root = leftRotate(root);
}
return (root.right == null) ? root :leftRotate(root);
}
}
static node bstSearch(node root, int key)
{
return splay(root, key);
}
static void preOrder(node root)
{
if (root != null)
{
System.out.print(root.key + " ");
preOrder(root.left);
preOrder(root.right);
}
}
public static void main(String args[])
{
node root = TreeNode(100);
root.left = TreeNode(50);
root.right = TreeNode(200);
root.left.left = TreeNode(40);
root.left.left.left = TreeNode(30);
root.left.left.left.left = TreeNode(2);
root = bstSearch(root, 20);
preOrder(root);
}
}
Output:
20 50 30 40 100 200
EXP. NO.5
DATE:
CREATING A BINARY TREE OF INTEGERS
AIM
To write a Java program to creating a binary tree of integers.
ALGORITHM
import java.io.*;
importjava.util.*;
classgfg
{
static class Node
{
publicint data;
public Node left,right;
public Node(intval)
{
this.data=val;
this.left=null;
this.right=null;
}
};
static void
PostPreInOrderInFlowRecursive(Noderoot,ArrayList<Integer>pre,ArrayList<Integ>post,ArrayList
<Integer>in)
{
if(root==null)
return;
pre.add(root.data);
PostPreInOrderInFlowRecursive(root.left,pre,post,in);
in.add(root.data);
PostPreInOrderInFlowRecursive(root.right,pre,post,in);
post.add(root.data);
}
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.left.right=new Node(5);
root.right.left=new Node(6);
root.right.right=new Node(7);
ArrayList<Integer>pre=new ArrayList<>();
ArrayList<Integer>post=new ArrayList<>();
ArrayList<Integer>in=new ArrayList<>();
PostPreInOrderInFlowRecursive(root,pre,post,in);
System.out.println("pre order:");
for(int i:pre)
{
System.out.println(i+"");
}
System.out.println();
System.out.println("post order:");
for(int i:post)
{
System.out.println(i+"");
}
System.out.println();
System.out.println("in order:");
for(int i:in)
{
System.out.println(i+"");
}
}
}
Output:
pre order:
1
2
4
5
3
6
7
post order:
4
5
2
6
7
3
1
in order:
4
2
5
1
6
3
7
EXP. NO.6
DATE:
MINIMAL SPANNING TREE OF A GRAPH USING THE
PRIM’S ALGORITHM.
AIM
To write a program minimal spanning tree of a graph using prim’s algorithm.
ALGORITHM
PROGRAM:
importjava.util.Arrays;
classPGraph
{
public void prim(int G[][],int V)
{
int INF=9999999;
intno_edge;
boolean[]selected=new boolean[V];
Arrays.fill(selected,false);
no_edge=0;
System.out.println("Edge:Weight");
while(no_edge<V-1)
{
int min=INF;
int x=0;
int y=0;
for(int i=0;i<V;i++)
{
if(selected[i]==true)
{
for(int j=0;j<V;j++)
{
if(!selected[j]&&G[i][j]!=0)
{
if(min>G[i][j])
{
min=G[i][j];
x=i;
y=j;
}
}
}
}
}
System.out.println(x+"-"+y+":"+G[x][y]);
selected[y]=true;
no_edge++;
}}
public static void main(String args[])
{
PGraph g=new PGraph();
int V=5;
int[][]G={{0,7,75,0,0},{9,0,95,19,42},{75,95,0,51,66},{0,19,51,0,31},{0,42,66,3,1,0}
};
g.prim(G,V);
}
}
Output:
Edge:Weight
0-0:0
0-1:7
1-3:19
3-4:31
EXP. NO.7
DATE:
BREADTH FIRST SEARCH
AIM
To write a program for breadth first search.
ALGORITHM
PROGRAM:
importjava.util.Scanner;
public class BFS_Graph
{
finalint TRUE = 1;
finalint FALSE = 0;
finalint MAX = 20;
int[ ][ ] G = new int [MAX] [MAX];
int[] Visit = new int[MAX];
int [] q = new int [MAX];
int n,V1,V2;
intfront,rear;
BFS_Graph()
{
System.out.println("enter number of nodes");
Scanner obj = new Scanner(System.in);
n = Integer.parseInt(obj.nextLine());
for (int i=1; i<=n; i++)
Visit[i]=FALSE;
for(V1=1; V1<=n; V1++)
{
for(V2=1; V2<=n; V2++)
G[V1][V2] = FALSE;
}
front = rear = -1;
}
voidcreateGraph()
{
charans;
System.out.println("enter the edges with vertex no.starting from 1");
do
{
System.out.println("enter the vertices V1 & V2:");
Scanner obj = new Scanner(System.in);
V1 = obj.nextInt();
V2 = obj.nextInt();
if (V1>n || V2>n)
System.out.println("Invalid vertex number ");
else
{
G[V1][V2] = TRUE;
G[V2][V1] = TRUE;
}
System.out.println("want to add more edges (y/n)?");
ans = obj.next().charAt(0);
}
while ((ans== 'y')||(ans== 'Y'));
}
void matrix()
{
System.out.println("adjacency matrix for the graph is");
for (int V1=1; V1<=n; V1++)
{
for(int V2=1; V2<=n; V2++)
System.out.print(G[V1][V2] + " ");
System.out.println();
}
}
voidbfs(int v)
{
int i;
Visit[v] = TRUE;
q[++rear] = v;
while (front != rear)
{
v = q[++front];
System.out.println(v + "");
for(i=1; i<=n; i++)
{
if (G[v][i] == TRUE && Visit[i] == FALSE)
{
q[++rear] = i;
Visit[i] = TRUE;
}
}
}
}
public static void main(String[] args)
{
System.out.println("PROGRAM TO CREATE A GRAPH AND TRAVERSE IN BFS
MANNER");
BFS_Graph g = new BFS_Graph();
g.createGraph();
g.matrix();
System.out.println("breadth first traverse for the above graph is");
g.bfs(1);
}}
Output:
AIM
To write a Java program that implement shell sort method.
ALGORITHM
PROGRAM:
classshellsort
{
static void printarray(intarr[])
{
int n=arr.length;
for(int i=0;i<n;i++)
System.out.println(arr[i]+"");
System.out.println();
}
int sort(intarr[])
{
int n=arr.length;
for(int gap=n/2;gap>0;gap/=2)
{
for(int i=gap;i<n;i+=1)
{
int temp=arr[i];
int j;
for(j=i;j>=gap&&arr[j-gap]>temp;j-=gap)
arr[j]=arr[j-gap];
arr[j]=temp;
}
}
return 0;
}
public static void main(String args[])
{
intarr[]={12,34,54,2,3};
System.out.println("array before sorting");
printarray(arr);
shellsortob=new shellsort();
ob.sort(arr);
System.out.println("array after sorting");
printarray(arr);
}
}
Output:
AIM
To implement using java generic class ,the queue its operation.
ALGORITHM
PROGRAM:
import java.io.*;
import java.util.*;
class queue<T>
{
int front=-1,rear=-1;
ArrayList<T>list=new ArrayList<>();
T front()
{
if(front==-1)
return null;
return list.get(front);
}
T rear()
{
if(rear==-1)
return null;
return list.get(rear);
}
void enqueue(T X)
{
if(this.empty())
{
front=0;
rear=0;
list.add(X);
}
else
{
front++;
if(list.size()>front){
list.add(front,X);
}
else
list.add(X);
}}
void dequeue()
{
if(this.empty())
System.out.println("queue is already empty");
else if(front==rear)
{
front=rear=-1;
}
else
{
rear++;
}}
boolean empty()
{
if(front==-1&&rear==-1)
return true;
return false;
}
public String toString()
{
if(this.empty())
return"";
String ans="";
for(int i=rear;i<front;i++){
ans+=String.valueOf(list.get(i))+"->";
}
ans+=String.valueOf(list.get(front));
return ans;
}
public static void main(String args[])
{
queue<Integer>q=new queue<>();
q.enqueue(10);
q.enqueue(15);
q.enqueue(20);
System.out.println("\n after enqueue of element"+q);
q.dequeue();
System.out.println("after dequeue:\n"+q);
queue<String>q1=new queue<>();
q1.enqueue("coding");
q1.enqueue("ninjas");
System.out.println("after enqueue of element:\n"+q1);
System.out.println("q1 front="+q1.front()+",q1 rear="+q1.rear());
}}
Output:
AIM
To write a Java program to create a doubly linked list implementation.
ALGORITHM
class Dll
{
node head;
class node
{
int data;
node prev;
node next;
node(int d){data=d;}
}
public void push(int new_data)
{
node new_node=new node(new_data);
new_node.next=head;
new_node.prev=null;
if(head!=null)
head.prev=new_node;
head=new_node;
}
public void insertbefore(node next_node,int new_data)
{
if(next_node==null)
{
System.out.println("the given next node can't be null");
return;
}
node new_node=new node(new_data);
new_node.prev=next_node.prev;
next_node.prev=new_node;
new_node.next=next_node;
if(new_node.prev!=null)
new_node.prev.next=new_node;
else
head=new_node;
}
public void insertafter(node prev_node,int new_data)
{
if(prev_node==null)
{
System.out.println("the given previous node can't be null");
return;
}
node new_node=new node(new_data);
new_node.next=prev_node.next;
prev_node.next=new_node;
new_node.prev=prev_node;
if(new_node.next!=null)
new_node.next.prev=new_node;
}
void append(int new_data)
{
node new_node=new node(new_data);
node last=head;
new_node.next=null;
if(head==null)
{
new_node.prev=null;
head=new_node;
return;
}
while(last.next!=null)
last=last.next;
last.next=new_node;
new_node.prev=last;
}
public void printlist(node node)
{
node last=null;
System.out.println("traversal in forward direction:");
while(node!=null){
System.out.println(node.data+"");
last=node;
node=node.next;
}
System.out.println();
System.out.println("traversal in backward direction:");
while(last!=null){
System.out.println(last.data+"");
last=last.prev;
}}
public static void main(String args[])
{
Dll dll=new Dll();
dll.append(6);
dll.push(7);
dll.push(1);
dll.append(4);
dll.insertafter(dll.head.next,8);
System.out.println("created Dll is:");
dll.printlist(dll.head);
}
}
Output:
ALGORITHM
import java.io.*;
public class linkedlist
{
node head;
static class node
{
int data;
node next;
node(int d)
{
data=d;
next=null;
}}
public static linkedlist insert(linkedlist list,int data)
{
node new_node=new node(data);
new_node.next=null;
if(list.head==null)
{
list.head=new_node;
new_node.next=null;
}
else{
node last=list.head;
while(last.next!=null)
{
last=last.next;
}
last.next=new_node;
}
return list;
}
public static void printlist(linkedlist list)
{
node currnode=list.head;
System.out.println("\n linked list:");
while(currnode!=null)
{
System.out.println(currnode.data+"");
currnode=currnode.next;
}
System.out.println("\n");
}
public static linkedlist deleteByKey(linkedlist list,int key)
{
node currnode=list.head,prev=null;
if(currnode!=null&&currnode.data==key)
{
list.head=currnode.next;
System.out.println(key+"found and deleted");
return list;
}
while(currnode!=null&&currnode.data!=key)
{
prev=currnode;
currnode=currnode.next;
}
if(currnode!=null)
{
prev.next=currnode.next;
System.out.println(key+"found and delete");
}
if(currnode==null)
{
System.out.println(key+"not found");
}
return list;
}
public static linkedlist deleteAtPosition(linkedlist list,int index)
{
node currnode=list.head,prev=null;
if(index==0 && currnode!=null)
{
list.head=currnode.next;
System.out.println(index+"position element deleted");
return list;
}
int counter=0;
while(currnode!=null)
{
if(counter==index){
prev.next=currnode.next;
System.out.println(index+"position element deleted");
break;
}
else{
prev=currnode;
currnode=currnode.next;
counter++;
}}
if(currnode==null){
System.out.println(index+"position element not found");
}
return list;
}
public static void main(String args[])
{
linkedlist list=new linkedlist();
list=insert(list,1);
list=insert(list,2);
list=insert(list,3);
list=insert(list,4);
list=insert(list,5);
printlist(list);
deleteByKey(list,1);
printlist(list);
deleteByKey(list,4);
printlist(list);
deleteByKey(list,10);
printlist(list);
deleteAtPosition(list,0);
printlist(list);
deleteAtPosition(list,2);
printlist(list);
deleteAtPosition(list,10);
printlist(list);
}
}
Output:
linked list:
1
2
3
4
1found and deleted linked list:
2
3
4
4found and delete linked list:
2
3
10not found linked list:
2
3
0position element deleted linked list:
3
2position element not found linked list:
3
10position element not found linked list:
3
EX.NO:12
DATE:
BELLMAN-FORD’S ALGORITHM
AIM
To write a program find the shortest path using Bellman ford's Algorithm.
ALGORITHM
class GFG
{
static void Bellmanford(int graph[][],int V,int E,int src)
{
int[]dis=new int[V];
for(int i=0;i<V;i++)
dis[i]=Integer.MAX_VALUE;
dis[src]=0;
for(int i=0;i<V-1;i++)
{
for(int j=0;j<E;j++)
{
if(dis[graph[j][0]]!=Integer.MAX_VALUE&&dis[graph[j][0]]+graph[j][2]<dis[graph[j][1]])
dis[graph[j][1]]=dis[graph[j][0]]+graph[j][2];
}}
for(int i=0;i<E;i++)
{
int x=graph[i][0];
int y=graph[i][1];
int weight=graph[i][2];
if(dis[x]!=Integer.MAX_VALUE&&dis[x]+weight<dis[y])
System.out.println("graph contain negative"+"weight cycle");}
System.out.println("vertex distance from source");
for(int i=0;i<V;i++)
System.out.println(i+"\t\t"+dis[i]);
}
public static void main(String args[])
{
int V=5;
int E=8;
int graph[][]={{0,1,-1},{0,2,4},{1,2,3},{1,3,2},{1,4,2},{3,2,5},{3,1,1},{4,3,-2}};
Bellmanford(graph,V,E,0);
}}
Output:
1
vertex distance from source
0 0
1 -1
2 2
3 -1
4
EXP.NO:13
DATE: IMPLEMENTING AVL TREE
AIM
ALGORITHM
import java.util.Scanner;
class Node
{
int element; int
h;
Node leftChild;
Node rightChild;
public Node()
{
leftChild = null;
rightChild = null;
element = 0;
h = 0;
}
public Node(int element)
{
leftChild = null; rightChild =
null; this.element = element;
h = 0;
}
}
class ConstructAVLTree
{
private Node rootNode; public
ConstructAVLTree()
{
rootNode = null;
}
if (head != null)
{
inorderTraversal(head.leftChild);
System.out.print(head.element+" ");
inorderTraversal(head.rightChild);
}
}
public void preorderTraversal()
{
preorderTraversal(rootNode);
}
private void preorderTraversal(Node head)
{
if (head != null)
{
System.out.print(head.element+" ");
preorderTraversal(head.leftChild);
preorderTraversal(head.rightChild);
}
}
public void postorderTraversal()
{
postorderTraversal(rootNode);
}
private void postorderTraversal(Node head)
{
if (head != null)
{
postorderTraversal(head.leftChild);
postorderTraversal(head.rightChild);
System.out.print(head.element+" ");
}
}
}
public class AVLTreeExample
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); ConstructAVLTree
obj = new ConstructAVLTree();
char choice; do
{
System.out.println("\nSelect an operation:\n");
System.out.println("1. Insert a node");
System.out.println("2. Search a node");
System.out.println("3. Get total number of nodes in AVL Tree");
System.out.println("4. Is AVL Tree empty?"); System.out.println("5.
Remove all nodes from AVL Tree"); System.out.println("6. Display AVL
Tree in Post order"); System.out.println("7. Display AVL Tree in Pre
order"); System.out.println("8. Display AVL Tree in In order");
int ch = sc.nextInt();
switch (ch)
{
case 1 :
System.out.println("Please enter an element to insert in AVL Tree");
obj.insertElement( sc.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to search");
System.out.println(obj.searchElement( sc.nextInt() )); break;
case 3 : System.out.println(obj.getTotalNumberOfNodes());
break;
case 4 : System.out.println(obj.checkEmpty());
break;
case 5 :
obj.removeAll();
System.out.println("\nTree Cleared successfully"); break;
case 6 :
System.out.println("\nDisplay AVL Tree in Post order");
obj.postorderTraversal();
break;
case 7 :
System.out.println("\nDisplay AVL Tree in Pre order");
obj.preorderTraversal();
break;
case 8 :
System.out.println("\nDisplay AVL Tree in In order");
obj.inorderTraversal();
break;
default :
System.out.println("\n ");
break;
}
System.out.println("\nPress 'y' or 'Y' to continue \n"); choice =
sc.next().charAt(0);
} while (choice == 'Y'|| choice == 'y');
}
}
Output:
Selection an operation:
1. Insert a node
2. Search a node
3. Get total number of node in AVL tree
4. Is AVL tree empty?
5. Remove all nodes from AVL tree
6. Display AVL tree in post order
7. Display AVL tree in pre order
8. Display AVL tree in In order
1
Please enter an element to insert in AVL tree
23
EXP.NO:14
DATE: IMPLEMENT A KRUSKAL'S ALGORITHAM
AIM
ALGORITHM
Program:
import java.util.*;
class Graph {
class Edge implements Comparable<Edge> {
int src, dest, weight;
public int compareTo(Edge compareEdge) {
return this.weight - compareEdge.weight;
}
};
class subset {
int parent, rank;
};
int vertices, edges;
Edge edge[];
Graph(int v, int e) {
vertices = v;
edges = e;
edge = new Edge[edges];
for (int i = 0; i < e; ++i)
edge[i] = new Edge();
}
int find(subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
void Union(subset subsets[], int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
}
i = 0;
while (e < vertices - 1) {
Edge next_edge = new Edge();
next_edge = edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
}
for (i = 0; i < e; ++i)
System.out.println(result[i].src + " - " + result[i].dest + ": " + result[i].weight);
}
public static void main(String[] args) {
int vertices = 6;
int edges = 8;
Graph G = new Graph(vertices, edges);
G.edge[0].src = 0;
G.edge[0].dest = 1;
G.edge[0].weight = 4;
G.edge[1].src = 0;
G.edge[1].dest = 2;
G.edge[1].weight = 4;
G.edge[2].src = 1;
G.edge[2].dest = 2;
G.edge[2].weight = 2;
G.edge[3].src = 2;
G.edge[3].dest = 3;
G.edge[3].weight = 3;
G.edge[4].src = 2;
G.edge[4].dest = 5;
G.edge[4].weight = 2;
G.edge[5].src = 2;
G.edge[5].dest = 4;
G.edge[5].weight = 4;
G.edge[6].src = 3;
G.edge[6].dest = 4;
G.edge[6].weight = 3;
G.edge[7].src = 5;
G.edge[7].dest = 4;
G.edge[7].weight = 3;
G.KruskalAlgo();
}
}
Output:
1 - 2: 2
2 - 5: 2
2 - 3: 3
3 - 4: 3
0 - 1: 4
EX.NO:15 IMPLEMENT A GRAPH TRAVERSING
DATE: ALGORITHAM
AIM
ALGORITHM
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import
java.util.Queue;
public class BreadthFirstSearchExampleNeighbourList
{
private Queue<Node> queue;
static ArrayList<Node> nodes=new ArrayList<Node>(); 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;
}
}
public BreadthFirstSearchExampleNeighbourList()
{
queue = new LinkedList<Node>();
}
public void bfs(Node node)
{
queue.add(node);
node.visited=true;
while (!queue.isEmpty())
{
Node element=queue.remove();
System.out.print(element.data + "t");
List<Node> neighbours=element.getNeighbours(); for (int i
= 0; i < neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited)
{
queue.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);
System.out.println("The BFS traversal of the graph is ");
BreadthFirstSearchExampleNeighbourList bfsExample = new
BreadthFirstSearchExampleNeighbourList();
bfsExample.bfs(node40);
}
}
OUTPUT:
40t10t20t30t60t50t70t