Post on 03-Jun-2018
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
1/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 1
INDEX
Sr.
Num
Name of Exper iment Page
Num
Lab
01
Recursion.
Program to demonstrate recursion to find the factorial of a given number.Program to demonstrate the use of recursion to display the Fibonacci sun of a given.
Program to demonstrate the use of recursion to solve tower of Hanoi game.
Lab
02
Recursion continued...
Program to demonstrate the use of recursion to find bp
.
Program to demonstrate the use of recursion to find sum of series for the first n
squares.
Program to demonstrate the use of recursion to find sum of series for the first n
power of base b.
Lab
03
Recursion continued...
Program to demonstrate the use of recursion to find the GCD of given two numbers.
Program to demonstrate the use of recursion to check the given string is a
palindrome.
Program to demonstrate the use of recursion to display the anagrams of a given
string.
Lab
04
Recursion continued...
Program to demonstrate the use of recursion to find the solution for n queen'sproblem.
Lab
05
Traversal of a Binary Search Tree
Program to implement INORDER traversal of a binary search tree.
Exam
Mid I
This exam counts 25% towards the final exam of students.
Format of Exam will be
a. 40% marks for writing program code
b. 30% for correct program execution
c. 30% for viva
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
2/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 2
Sr.Num
Name of Exper iment PageNum
Lab
06
Traversal of a Binary Search Tree Continued
Program to implement PREORDER traversal of a binary search tree.
Lab
07
Traversal of a Binary Search Tree Continued
Program to implement POSTORDER traversal of a binary search tree.
Lab
08
Traversal of an AVL Tree
Program to implement traversal of an AVL tree.
Lab
09
Implementation of a BTree
Program to implement a BTree.
Lab
10
Understanding Hash Table
Program to understand a Hash Table.
Lab
11
Implementation of BFS for a Graph
Program to implement BFS for a Graph.
Lab
12
Implementation of DFS for a Graph
Program to implement DFS for a Graph.
Lab
13 Revision
Final
Exam
This exam counts 50% towards the final exam of students.
Format of Exam will be
d. 40% marks for writing program code
e. 30% for correct program execution
f. 30% for viva
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
3/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 3
INSTRUCTIONS TO BE FOLLOWED IN MAINTAINING THE RECORD
BOOK
The Record should be written neatly with ink on the right hand page only. The left hand page
being reserved for diagrams.
The Record should contain:
1. The date2. The number and name of the experiment
3.
The aim of the experiment4. Algorithm
5. Program6. On the left hand side, Flow charts should be designed
7. On the left hand side, Input & Output should be mentioned.8. Index must be filled in regularly.
9. You must get your record certified by the concerned staff on the very next class aftercompleting the experiment
10.You must get your record certified by the concerned staff at the end of every semester.
INSTRUCTIONS TO BE FOLLOWED IN THE LABORATORY
1. You must bring record observations notebook, while coming to the practical class without you maynot be allowed to the practical.
2. Dont touch the equipment which is not connected with our experiment.
3. When the system /apparatus is issued, you are advised to check their conditions.
4. You should not leave the laboratory without obtaining the signature of the concerned lecturer after
completing the practicalNote:
1.Damaged caused to the property of the laboratory will be recovered2. If 75 % of the experiments prescribed are not completed the candidate will not be allowed for
attending examinations.
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
4/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 4
Lab 01: RecursionAim:The purpose of this lab is to understand recursion.
i. Why recursion?ii. How recursion works?
Program 01:
Program to demonstrate the use of recursion to f ind the factorial of a given number.
Source code
import javax.swing.*;class Fact{
int num;public void read()
{num=Integer.parseInt(JOptionPane.showInputDialog(null ,"Enter a
Number: "));}
public int factorial(int n)
{if(n==0)
return 1;return n*factorial(n-1);
}
public static void main(String []args){
Fact f=new Fact();f.read();
int result=f.factorial(f.num);
JOptionPane.showMessageDialog(null," The Factorial of a Number is: "+result);}
}//End
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
5/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 5
Program 02:
Program to demonstrate the use of recursion to display the Fibonacci sun of a given. number.
Source codeimport javax.swing.*;class Fibona
{int num;
public void read(){
num=Integer.parseInt(JOptionPane.showInputDialog(null ,"Enter aNumber: "));
}
public long fibonacci(int n){
if(n
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
6/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 6
Program 03:
Program to demonstrate the use of recursion to solve tower of Hanoi game.
Source code
class Tower{
public static void main(String args[]){
runHanoi(3,'A','B','C');}
public static void runHanoi(int n,char x,char y,char z)
{if(n==1)
System.out.println("Move top disk from tower "+ x +" to tower"+z);
else{
runHanoi(n-1,x,z,y); //recursionrunHanoi(1,x,y,z); //recursion
runHanoi(n-1,y,x,z); //recursion
}}
}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
7/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 7
Lab 02: Recursion ContinuedAim:The purpose of this lab is to understand recursion.
Program 01:
Program to demonstrate the use of recursion to f ind bp.
Source codeimport javax.swing.*;
class Calculatepower
{static int x,n;public void read()
{x=Integer.parseInt(JOptionPane.showInputDialog(null ,"Enter the BASE
number:"));n=Integer.parseInt(JOptionPane.showInputDialog(null ,"Enter the
POWER number: "));}
public static int power(int x, int n)
{if (n==0)
return 1;else
return x*power(x,n-1);}
public static void main(String args[])
{int result;
Calculatepower p=new Calculatepower();
p.read();result=Calculatepower.power(x,n);JOptionPane.showMessageDialog(null,"The x power n result is: "+result);
}}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
8/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 8
Program 02:
Program to demonstrate the use of recursion to f ind sum of seri es for the f irst n squares.
Source codeimport javax.swing.*;class s1
{int n;
public void read(){
n=Integer.parseInt(JOptionPane.showInputDialog(null ,"Enter a Number:"));
}
public int sum1(int n){
if(n==0)return 0;
return sum1(n-1)+n*n;
}
public static void main(String []args)
{s1 s=new s1();//object creation
s.read();int result=s.sum1(s.n);
JOptionPane.showMessageDialog(null," The sum of a Number is: "+result);
}}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
9/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 9
Program 03:
Program to demonstrate the use of recursion to f ind sum of seri es for the f irst n power of base b.
Source codeimport javax.swing.*;
class s2{
int p;double b;
public void read(){
p=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a Numberfor POWER: "));
b=Double.parseDouble(JOptionPane.showInputDialog(null,"Enter aNumber for BASE: "));
}
public double sum2(double b,int p){
if(p==0)
return 1;return 1+b*sum2(b,p-1);
}
public static void main(String []args)
{s2 s=new s2();//object creation
s.read();double result=s.sum2(s.b,s.p);
JOptionPane.showMessageDialog(null," The sum of a Numbers is: "+result);
}}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
10/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 10
Lab 03: Recursion ContinuedAim:The purpose of this lab is to understand recursion.
Program 01:
Program to demonstrate the use of recursion to f ind the GCD of given two numbers.
Source code/*Recursive gcd() (Greatest common divisor) (or) Euclidean Algorithm for gcd */import javax.swing.*;
class Euclidean
{static int m,n;public void read()
{m=Integer.parseInt(JOptionPane.showInputDialog(null ,"Enter the first
number: "));n=Integer.parseInt(JOptionPane.showInputDialog(null ,"Enter the second
number: "));}
public static int gcd(int m, int n)
{if (m==0) return n;
if (n==0) return m;else if(m
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
11/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 11
Program 02:
Program to demonstrate the use of recursion to check the given str ing is a palindrome.
Source code
import javax.swing.*;class Palin
{public static boolean palindrom(String word)
{boolean result=true;
if(word.length()==1||word.length()==0)System.out.println("Enter a Word");
else if(word.charAt(0)==word.charAt(word.length()-1))result=palindrom(word.substring(0+1,word.length()-1));
elseresult=false;
return result;}
public static void main(String []args){
String name=JOptionPane.showInputDialog(null,"Enter a String To
Check");JOptionPane.showMessageDialog(null,"The String "+name+" is =
"+palindrom(name));}
}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
12/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 12
Program 03:
Program to demonstrate the use of recursion to display the anagrams of a given str ing.
Source codeimport java.io.*;class AnagramApp
{static int size, count;
static char[] arrChar = new char[100];public static void main(String[] args) throws IOException
{System.out.print("Enter a word: ");
String input = getString();size = input.length();
count = 0;for(int j=0; j
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
13/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 13
public static void displayWord()
{if(count < 99) System.out.print(" ");
if(count < 9) System.out.print(" ");System.out.print(++count + " ");for(int j=0; j
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
14/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 14
public static void printQueens(int[] q)
{int N = q.length;
for (int i = 0; i < N; i++){
for (int j = 0; j < N; j++)
{if (q[i] == j) System.out.print("Q ");
else System.out.print("* ");}
System.out.println();}
System.out.println();}
public static void enumerate(int N){
int[] a = new int[N];enumerate(a, 0);
}public static void enumerate(int[] q, int n)
{int N = q.length;
if (n == N) printQueens(q);
else{
for (int i = 0; i < N; i++)
{q[n] = i;
if (isConsistent(q, n))enumerate(q, n+1);
}}
}public static void main(String[] args)
{String str;
int N;str = JOptionPane.showInputDialog(null, "Enter number of queens");
N = Integer.parseInt(str);enumerate(N);
}}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
15/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 15
Lab 05: Traversal of a Binary Search TreeAim:The purpose of this lab is to understand and implement the different ways to traverse a binary searchtree.
Program 01:
Program to implement INORDER traversal of a binary search tr ee.
Source codeimport javax.swing.*;
class BinaryTree
{int data;BinaryTree left,right;
BinaryTree(int x)
{this.left=this.right=null;
data=x;}
public void insert( int i )
{if (i = data){
if (right != null)
right.insert(i);elseright = new BinaryTree( i );
}}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
16/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 16
public void inOrder(BinaryTree tree)
{if(tree!=null){
inOrder(tree.left);System.out.print(tree.data+" ");
inOrder(tree.right);}
}
public static void main (String args[]){
char choice='y';int n;
String s=JOptionPane.showInputDialog(null,"Enter node value");n=Integer.parseInt(s);
s=JOptionPane.showInputDialog(null,"Enter ur Choice(y/n)");choice=s.charAt(0);
BinaryTree ob=new BinaryTree(n);while (choice=='y')
{
s=JOptionPane.showInputDialog(null,"Enter node value");n=Integer.parseInt(s);ob.insert(n);
s=JOptionPane.showInputDialog(null,"Enter ur Choice(y/n)");choice=s.charAt(0);
}
System.out.println("Inorder Traversal");ob.inOrder(ob);System.out.println("");
}
}//End
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
17/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 17
Lab 06: Traversal of a Binary Search Tree ContinuedAim:The purpose of this lab is to understand and implement the different ways to traverse a binary search
tree.
Program 01:
Program to implement PREORDER traversal of a binarysearch tree.
Source codeimport javax.swing.*;
class BinaryTree{
int data;BinaryTree left,right;BinaryTree(int x)
{this.left=this.right=null;
data=x;}
public void insert( int i ){
if (i = data)
{if (right != null)right.insert(i);
elseright = new BinaryTree( i );}
}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
18/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 18
public void preOrder(BinaryTree tree){
if(tree!=null)
{System.out.print(tree.data+" ");preOrder(tree.left);
preOrder(tree.right);}
}
public static void main (String args[]){
char choice='y';
int n;String s=JOptionPane.showInputDialog(null,"Enter node value");n=Integer.parseInt(s);s=JOptionPane.showInputDialog(null,"Enter ur Choice(y/n)");
choice=s.charAt(0);BinaryTree ob=new BinaryTree(n);while (choice=='y')
{
s=JOptionPane.showInputDialog(null,"Enter node value");n=Integer.parseInt(s);ob.insert(n);
s=JOptionPane.showInputDialog(null,"Enter ur Choice(y/n)");choice=s.charAt(0);
}
System.out.println("Pre-order Traversal");ob.preOrder(ob);System.out.println("");
}
}//End
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
19/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 19
Lab 07: Traversal of a Binary Tree Search ContinuedAim:The purpose of this lab is to understand and implement the different ways to traverse a binary search
tree.
Program 01:
Program to implement POSTORDER traversal of a binarysearch tree.
Source code
import javax.swing.*;class BinaryTree{
int data;
BinaryTree left,right;
BinaryTree(int x){
this.left=this.right=null;data=x;
}
public void insert( int i ){
if (i = data)
{
if (right != null)right.insert(i);else
right = new BinaryTree( i );}
}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
20/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 20
public void postOrder(BinaryTree tree)
{
if(tree!=null){
postOrder(tree.left);
postOrder(tree.right);System.out.print(tree.data+" ");
}
}public static void main (String args[]){
char choice='y';
int n;String s=JOptionPane.showInputDialog(null,"Enter node value");n=Integer.parseInt(s);s=JOptionPane.showInputDialog(null,"Enter ur Choice(y/n)");
choice=s.charAt(0);BinaryTree ob=new BinaryTree(n);while (choice=='y')
{
s=JOptionPane.showInputDialog(null,"Enter node value");n=Integer.parseInt(s);ob.insert(n);
s=JOptionPane.showInputDialog(null,"Enter ur Choice(y/n)");choice=s.charAt(0);
}
System.out.println("");System.out.println("Post Order Traversal");ob.postOrder(ob);System.out.println("");
}
}//End
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
21/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 21
Lab 08: Traversal of an AVL TreeAim:The purpose of this lab is to understand and implement traversal an AVL tree.
Program 01:
Program to implement traversal of an AVL tree.
Source code
public class AVLTreeInsert
{public static void main(String[] args)
{new AVLTreeInsert().run();
}
static class Node
{Node left;Node right;
int value;public Node(int value)
{this.value = value;
}}
public void run(){
Node rootnode = new Node(25);
System.out.println("Building tree with root value " + rootnode.value);System.out.println("=================================");insert(rootnode, 11);
insert(rootnode, 15);insert(rootnode, 16);insert(rootnode, 23);insert(rootnode, 79);
}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
22/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 22
public void insert(Node node, int value)
{
if (value < node.value){
if (node.left != null)
{insert(node.left, value);
}
else{
System.out.println(" Inserted " + value + " to left of Node " + node.value);
node.left = new Node(value);
}}else if (value > node.value){
if (node.right != null){
insert(node.right, value);
}
else{
System.out.println(" Inserted " + value + " to right of Node " + node.value);
node.right = new Node(value);}
}
}}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
23/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 23
Lab 09: Implementation of a BTreeAim:The purpose of this lab is to understand and implement a BTree.
Program 01:
Program to implement a BTree.
Source codeclass BTree{
final int MAX = 4;
final int MIN = 2;//15 21 35 42 29 11 12 18 20 23 25 27 31 33 36 39 45 47 50 55 B-Tree of order 5class BTNode
{int count;
int key[] = new int[MAX+1];BTNode child[] = new BTNode[MAX+1];
}
BTNode root = new BTNode();
class Ref{
int m;
}public void insertTree( int val )
{
Ref i = new Ref();BTNode c = new BTNode();BTNode node = new BTNode();Boolean pushup;
pushup = pushDown( val, root, i, c );if ( pushup )
{node.count = 1;node.key[1] = i.m;
node.child[0] = root;node.child[1] = c;
root = node;}
}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
24/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 24
boolean pushDown( int val, BTNode node, Ref p, BTNode c )
{Ref k = new Ref();if ( node == null )
{
p.m = val;c = null;return true;
}else{
if ( searchNode( val, node, k ) )System.out.println("Key already exists.");
if ( pushDown( val, node.child[k.m], p, c ) )
{
if ( node.count < MAX ){
pushIn( p.m, c, node, k.m );return false;
}else{
split( p.m, c, node, k.m, p, c );
return true;}
}
return false;}
}
BTNode searchTree( int val, BTNode root, Ref pos )
{
if ( root == null ) return null ;else
{if ( searchNode( val, root, pos ) )return root;elsereturn searchTree( val, root.child[pos.m], pos );
}}
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
25/35
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
26/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 26
newnode.count = MAX - mid;node.count = mid;
if ( k
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
27/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 27
Lab 10: Understanding Hash TableAim:The purpose of this lab is to understand a Hash Table.
Program 01:
Program to understand a Hash Table.
Source codeimport java.util.*;
import java.io.*;class HashTable
{ public static void main(String[] args) throws IOException
{int key;try
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));System.out.print
("How many elements you want to enter to the hash table : ");int n = Integer.parseInt(in.readLine());Hashtable hashTable = new
Hashtable();for(int i = 0; i < n; i++){
System.out.print("Enter key for the hash table : ");
key = Integer.parseInt(in.readLine());System.out.print("Enter value for the key : ");hashTable.put(key, in.readLine());
}
Map map = newTreeMap(hashTable);System.out.println(map);
}catch(NumberFormatException ne)
{System.out.println(ne.getMessage() + " is not a legal value.");
System.out.println("Please enter a numeric value.");System.exit(1);
}
}}//End
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
28/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 28
Lab 11: Implementation of BFS for a GraphAim:The purpose of this lab is to understand and implement BFS for a Graph.
Program 01:
Program to implement BFS for a Graph.
Source codeclass Queue{
private final int SIZE = 20;private int[] queArray;private int front;private int rear;
public Queue() // constructor{
queArray = new int[SIZE];front = 0;rear = -1;
}
public void insert(int j) // put item at rear of queue{
if(rear == SIZE-1)
rear = -1;queArray[++rear] = j;
}
public int remove() // take item from front of queue{
int temp = queArray[front++];
if(front == SIZE)
front = 0;return temp;
}
public boolean isEmpty() // true if queue is empty
{return ( rear+1==front || (front+SIZE-1==rear) );
}
} // end class Queue
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
29/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 29
class Vertex
{public char label; // label (e.g. 'A')public boolean wasVisited;
public Vertex(char lab) // constructor{
label = lab;
wasVisited = false;}
} // end class Vertex
class Graph{
private final int MAX_VERTS = 20;
private Vertex vertexList[]; // list of verticesprivate int adjMat[][]; // adjacency matrixprivate int nVerts; // current number of verticesprivate Queue theQueue;
public Graph() // constructor{
vertexList = new Vertex[MAX_VERTS];
// adjacency matrixadjMat = new int[MAX_VERTS][MAX_VERTS];nVerts = 0;for(int j=0; j
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
30/35
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
31/35
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
32/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 32
Lab 12: Implementation of DFS for a GraphAim:The purpose of this lab is to understand and implement DFS for a Graph.
Program 01:
Program to implement DFS for a Graph.
Source code
class StackX
{private final int SIZE = 20;
private int[] st;private int top;
public StackX() // constructor{
st = new int[SIZE]; // make arraytop = -1;
}
public void push(int j) // put item on stack
{st[++top] = j;
}
public int pop() // take item off stack
{return st[top--];
}
public int peek() // peek at top of stack{
return st[top];}
public boolean isEmpty() // true if nothing on stack{
return (top == -1);}
} // end class StackX
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
33/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 33
class Vertex{
public char label; // label (e.g. 'A')public boolean wasVisited;
public Vertex(char lab) // constructor{
label = lab;wasVisited = false;
}} // end class Vertex
class Graph
{private final int MAX_VERTS = 20;
private Vertex vertexList[]; // list of verticesprivate int adjMat[][]; // adjacency matrix
private int nVerts; // current number of verticesprivate StackX theStack;
public Graph() // constructor
{
vertexList = new Vertex[MAX_VERTS];// adjacency matrixadjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;for(int y=0; y
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
34/35
Department of Computer Science,
KING KHAL ID UNIVERSITY, ABHA
KINDDOM OF SAUDI ARABIA
LAB MANUALCS216 ( Algori thms & Data structures)
Issue : 01
Page 34
public void addEdge(int start, int end)
{adjMat[start][end] = 1;
adjMat[end][start] = 1;}
public void displayVertex(int v){
System.out.print(vertexList[v].label);}
public void dfs() // depth-first search{ // begin at vertex 0
vertexList[0].wasVisited = true; // mark itdisplayVertex(0); // display it
theStack.push(0); // push itwhile( !theStack.isEmpty() ) // until stack empty,{
// get an unvisited vertex adjacent to stack top
int v = getAdjUnvisitedVertex( theStack.peek() );if(v == -1) // if no such vertex,theStack.pop();
else // if it exists,
{vertexList[v].wasVisited = true; // mark itdisplayVertex(v); // display it
theStack.push(v); // push it}
} // end while
// stack is empty, so we're donefor(int j=0; j
8/11/2019 5 CSM 216_77_Labmannual Summer Semster (1)
35/35