0 évaluation0% ont trouvé ce document utile (0 vote)
94 vues35 pages
This document is a lab manual for an algorithms and data structures course. It outlines 13 labs covering topics like recursion, binary search trees, graphs, and hashing. Each lab includes 3 programming problems to demonstrate the topic. For example, Lab 1 on recursion includes programs to calculate factorial recursively, display the Fibonacci sequence recursively, and solve the Tower of Hanoi problem recursively. The document provides source code examples for each problem and instructions for students to document their work and follow protocols in the lab.
This document is a lab manual for an algorithms and data structures course. It outlines 13 labs covering topics like recursion, binary search trees, graphs, and hashing. Each lab includes 3 programming problems to demonstrate the topic. For example, Lab 1 on recursion includes programs to calculate factorial recursively, display the Fibonacci sequence recursively, and solve the Tower of Hanoi problem recursively. The document provides source code examples for each problem and instructions for students to document their work and follow protocols in the lab.
This document is a lab manual for an algorithms and data structures course. It outlines 13 labs covering topics like recursion, binary search trees, graphs, and hashing. Each lab includes 3 programming problems to demonstrate the topic. For example, Lab 1 on recursion includes programs to calculate factorial recursively, display the Fibonacci sequence recursively, and solve the Tower of Hanoi problem recursively. The document provides source code examples for each problem and instructions for students to document their work and follow protocols in the lab.
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
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
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
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
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
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
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
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 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 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
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
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
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 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;
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 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
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
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 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
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 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
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
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
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
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