Vous êtes sur la page 1sur 35

Department of Computer Science,

KING KHALID UNI VERSITY, ABHA


KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 1

INDEX

Sr.
Num
Name of Experiment 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 b
p
.
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's
problem.

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


Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 2

Sr.
Num
Name of Experiment Page
Num
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







Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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 date
2. The number and name of the experiment
3. The aim of the experiment
4. Algorithm
5. Program
6. 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 after
completing 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 may
not 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 practical
Note:

1. Damaged caused to the property of the laboratory will be recovered
2. If 75 % of the experiments prescribed are not completed the candidate will not be allowed for
attending examinations.

Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 4

Lab 01: Recursion

Aim:
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 find 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





Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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 code
import javax.swing.*;
class Fibona
{
int num;
public void read()
{
num=Integer.parseInt(JOptionPane.showInputDialog(null ,"Enter a
Number: "));
}

public long fibonacci(int n)
{
if(n<2) //basis part
return n;
return fibonacci(n-1) + fibonacci(n-2); //recursive part
}

public static void main(String args[])
{
Fibona f=new Fibona();
f.read();
long result=f.fibonacci(f.num);
JOptionPane.showMessageDialog(null,"The Fibonacci SUM is: "+result);
}
}//End














Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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); //recursion
runHanoi(1,x,y,z); //recursion
runHanoi(n-1,y,x,z); //recursion
}
}
}












Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 7

Lab 02: Recursion Continued

Aim:
The purpose of this lab is to understand recursion.

Program 01:
Program to demonstrate the use of recursion to find b
p
.

Source code
import 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);
}
}




Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 8





Program 02:
Program to demonstrate the use of recursion to find sum of series for the first n squares.

Source code
import 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);
}
}









Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 9




Program 03:
Program to demonstrate the use of recursion to find sum of series for the first n power of base b.

Source code
import javax.swing.*;
class s2
{
int p;
double b;
public void read()
{
p=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a Number
for POWER: "));
b=Double.parseDouble(JOptionPane.showInputDialog(null,"Enter a
Number 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);
}
}





Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 10

Lab 03: Recursion Continued
Aim:
The purpose of this lab is to understand recursion.

Program 01:
Program to demonstrate the use of recursion to find 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<n)
return gcd(m,n%m);
else
return gcd(m%n,n);
}

public static void main(String args[])
{
int result;
Euclidean g=new Euclidean();
g.read();
result=Euclidean.gcd(m,n);
JOptionPane.showMessageDialog(null,"The GCD of Two number is: "+result);
}
}


Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 11





Program 02:
Program to demonstrate the use of recursion to check the given string 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));
else
result=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));
}
}












Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 12

Program 03:
Program to demonstrate the use of recursion to display the anagrams of a given string.

Source code
import 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<size; j++)
arrChar[j] = input.charAt(j);
doAnagram(size);
} // end of main()

public static void doAnagram(int newSize)
{
if(newSize == 1) return;
for(int j=0; j<newSize; j++)
{
doAnagram(newSize-1);
if(newSize==2) displayWord();
rotate(newSize);
}
}

public static void rotate(int newSize)
{
int j;
int position = size - newSize;
char temp = arrChar[position];
for(j=position+1; j<size; j++)
arrChar[j-1] = arrChar[j];
arrChar[j-1] = temp;
}



Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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<size; j++)
System.out.print( arrChar[j] );
System.out.print(" ");
System.out.flush();
if(count%6 == 0) System.out.println(" ");
}
public static String getString() throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
}
}//End of class
Lab 04: Recursion Continued
Aim:
The purpose of this lab is to understand recursion.

Program 01:
Program to demonstrate the use of recursion to find the solution for n queens problem.

Source code
//n queens not attacking positions(using back track)
import javax.swing.*;
class Queens
{
public static boolean isConsistent(int[] q, int n)
{
for (int i = 0; i < n; i++)
{
if (q[i] == q[n]) return false; // same column
if ((q[i] - q[n]) == (n - i)) return false; // same major diagonal
if ((q[n] - q[i]) == (n - i)) return false; // same minor diagonal
}
return true;
}

Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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);
}
}

Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 15

Lab 05: Traversal of a Binary Search Tree
Aim:
The purpose of this lab is to understand and implement the different ways to traverse a binary search
tree.

Program 01:
Program to implement INORDER traversal of a binary search 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 (left != null)
left.insert(i);
else
left = new BinaryTree( i );
}
else if (i >= data)
{
if (right != null)
right.insert(i);
else
right = new BinaryTree( i );
}
}




Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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







Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 17

Lab 06: Traversal of a Binary Search Tree Continued

Aim:
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 binary search 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 (left != null)
left.insert(i);
else
left = new BinaryTree( i );
}
else if (i >= data)
{
if (right != null)
right.insert(i);
else
right = new BinaryTree( i );
}
}






Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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









Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 19

Lab 07: Traversal of a Binary Tree Search Continued

Aim:
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 binary search 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 (left != null)
left.insert(i);
else
left = new BinaryTree( i );
}
else if (i >= data)
{
if (right != null)
right.insert(i);
else
right = new BinaryTree( i );
}
}




Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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








Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 21

Lab 08: Traversal of an AVL Tree

Aim:
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);
}




Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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);
}
}
}
}









Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 23

Lab 09: Implementation of a BTree
Aim:
The purpose of this lab is to understand and implement a BTree.

Program 01:
Program to implement a BTree.

Source code
class 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 5
class 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;
}
}

Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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;
else
return searchTree( val, root.child[pos.m], pos );
}
}


Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 25

boolean searchNode( int val, BTNode node, Ref pos )
{
if ( val < node.key[1] )
{
pos.m = 0 ; return false ;
}
else
{
pos.m = node.count ;
while ( ( val < node.key[pos.m] ) && pos.m > 1 )
(pos.m)--;
if ( val == node.key[pos.m] )
return true;
else
return false;
}
}

void pushIn( int val, BTNode c, BTNode node, int k )
{
int i ;
for ( i = node.count; i > k ; i-- )
{
node.key[i + 1] = node.key[i];
node.child[i + 1] = node.child[i];
}
node.key[k + 1] = val ;
node.child[k + 1] = c ;
node.count++ ;
}

void split( int val, BTNode c, BTNode node, int k, Ref y, BTNode newnode )
{
int i, mid;
if ( k <= MIN )
mid = MIN;
else
mid = MIN + 1;
newnode = new BTNode();
for ( i = mid+1; i <= MAX; i++ )
{
newnode.key[i-mid] = node.key[i];
newnode.child[i-mid] = node.child[i];
}

Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 26

newnode.count = MAX - mid;
node.count = mid;
if ( k <= MIN )
pushIn ( val, c, node, k );
else
pushIn ( val, c, newnode, k-mid ) ;
y.m = node.key[node.count];
newnode.child[0] = node.child[node.count] ;
node.count-- ;
}

void displayTree()
{
display( root );
}

void display( BTNode root )
{
int i;
if ( root != null )
{
for ( i = 0; i < root.count; i++ )
{
display( root.child[i] );
System.out.print( root.key[i+1] + " " );
}
display( root.child[i] );
}
}
}

class BTreeDemo
{
public static void main( String[] args )
{
BTree bt = new BTree();
int[] arr = { 11, 23, 21, 12, 31, 18, 25, 35, 29, 20, 45, 27, 42, 55, 15, 33, 36, 47, 50, 39 };
for ( int i = 0; i < arr.length; i++ )
bt.insertTree( arr[i] );
System.out.println("B-Tree of order 5:");
bt.displayTree();
}
}

Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 27

Lab 10: Understanding Hash Table
Aim:
The purpose of this lab is to understand a Hash Table.

Program 01:
Program to understand a Hash Table.

Source code
import 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<Integer, String> hashTable = new
Hashtable<Integer, String>();
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<Integer, String> map = new
TreeMap<Integer, String>(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

Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 28

Lab 11: Implementation of BFS for a Graph

Aim:
The purpose of this lab is to understand and implement BFS for a Graph.

Program 01:
Program to implement BFS for a Graph.

Source code
class 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

Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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 vertices
private int adjMat[][]; // adjacency matrix
private int nVerts; // current number of vertices
private Queue theQueue;

public Graph() // constructor
{
vertexList = new Vertex[MAX_VERTS];
// adjacency matrix
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int j=0; j<MAX_VERTS; j++) // set adjacency
for(int k=0; k<MAX_VERTS; k++) // matrix to 0
adjMat[j][k] = 0;
theQueue = new Queue();
} // end constructor
public void addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}

public void addEdge(int start, int end)
{
adjMat[start][end] = 1;
adjMat[end][start] = 1;
}



Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 30




public void displayVertex(int v)
{
System.out.print(vertexList[v].label);
}

public void bfs() // breadth-first search
{ // begin at vertex 0
vertexList[0].wasVisited = true; // mark it
displayVertex(0); // display it
theQueue.insert(0); // insert at tail
int v2;
while( !theQueue.isEmpty() ) // until queue empty,
{
int v1 = theQueue.remove(); // remove vertex at head
// until it has no unvisited neighbors
while( (v2=getAdjUnvisitedVertex(v1)) != -1 )
{ // get one,
vertexList[v2].wasVisited = true; // mark it
displayVertex(v2); // display it
theQueue.insert(v2); // insert it
} // end while
} // end while(queue not empty)
// queue is empty, so we're done
for(int j=0; j<nVerts; j++) // reset flags
vertexList[j].wasVisited = false;
} // end bfs()

// returns an unvisited vertex adj to v
public int getAdjUnvisitedVertex(int v)
{
for(int j=0; j<nVerts; j++)
if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
return j;
return -1;
} // end getAdjUnvisitedVertex()

} // end class Graph





Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 31





class BFSApp
{
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0 (start for bfs)
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4
theGraph.addEdge(0, 1); // AB
theGraph.addEdge(1, 2); // BC
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(3, 4); // DE
System.out.print("Visits: ");
theGraph.bfs(); // breadth-first search
System.out.println();
} // end main()
} // end class BFSApp




















Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 32

Lab 12: Implementation of DFS for a Graph

Aim:
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 array
top = -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

Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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 vertices
private int adjMat[][]; // adjacency matrix
private int nVerts; // current number of vertices
private StackX theStack;

public Graph() // constructor
{
vertexList = new Vertex[MAX_VERTS];
// adjacency matrix
adjMat = new int[MAX_VERTS][MAX_VERTS];
nVerts = 0;
for(int y=0; y<MAX_VERTS; y++) // set adjacency
for(int x=0; x<MAX_VERTS; x++) // matrix to 0
adjMat[x][y] = 0;
theStack = new StackX();
} // end constructor

public void addVertex(char lab)
{
vertexList[nVerts++] = new Vertex(lab);
}






Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & 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 it
displayVertex(0); // display it
theStack.push(0); // push it
while( !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 it
displayVertex(v); // display it
theStack.push(v); // push it
}
} // end while
// stack is empty, so we're done
for(int j=0; j<nVerts; j++) // reset flags
vertexList[j].wasVisited = false;
} // end dfs

// returns an unvisited vertex adj to v
public int getAdjUnvisitedVertex(int v)
{
for(int j=0; j<nVerts; j++)
if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
return j;
return -1;
} // end getAdjUnvisitedVertex()
} // end class Graph

Department of Computer Science,
KING KHALID UNI VERSITY, ABHA
KINDDOM OF SAUDI ARABI A

LAB MANUAL
CS216 ( Algorithms & Data structures)
Issue : 01
Page 35


class DFSApp
{
public static void main(String[] args)
{
Graph theGraph = new Graph();
theGraph.addVertex('A'); // 0 (start for dfs)
theGraph.addVertex('B'); // 1
theGraph.addVertex('C'); // 2
theGraph.addVertex('D'); // 3
theGraph.addVertex('E'); // 4
theGraph.addEdge(0, 1); // AB
theGraph.addEdge(1, 2); // BC
theGraph.addEdge(0, 3); // AD
theGraph.addEdge(3, 4); // DE
System.out.print("Visits: ");
theGraph.dfs(); // depth-first search
System.out.println();
} // end main()
} // end class DFSApp

Vous aimerez peut-être aussi