Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Page 1 1) Write Java programs that use both recursive and non-recursive functions for implementing the following searching methods: a) Linear search b) Binary search a) Linear search import java.io.*; public class LinearSearch { public void lSrch(int key,int[] a) { for(int i=0;i<a.length;i++) { if(a[i]==key) { System.out.println("Element found at "+ (i+1)+"position"); return; } } System.out.println("Element not found"); } public void lRecurSrch(int[] a,int key,int i,int n) { if(i==n) { System.out.println("Element not found "); return; } if(a[i]==key) { System.out.println("Element found at " + (i+1) + "position"); return; } lRecurSrch(a,key,i+1,n); } public static void main(String[] args)throws IOException { LinearSearch ls=new LinearSearch(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int[] a=new int[20]; int i,n,key; System.out.println("Enter size of array: "); n=Integer.parseInt(br.readLine()); System.out.println("Enter elements of array: "); for(i=0;i<n;i++) a[i]=Integer.parseInt(br.readLine()); System.out.println("Enter key element to be search:"); Page 2 key=Integer.parseInt(br.readLine()); do { System.out.println("\n\tLinear Search"); System.out.println("*********"); System.out.println("1.Non-recursive\n2.Recursive\n3.Exit"); System.out.println("*********"); System.out.println("Enter your choice"); int ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: ls.lSrch(key,a); break; case 2: ls.lRecurSrch(a, key, 0, n); break; case 3: return; default: System.out.println("Invalid choice:"); } } while(true); } } /* Output: G:\Documents and Settings\Kishore >java LinearSearch Enter size of array: 5 Enter elements of array: 25 35 65 45 21 Enter key element to be search: 25 Linear Search ********* 1.Non-recursive 2.Recursive 3.Exit Page 3 ********* Enter your choice 1 Element found at 1position Linear Search ********* 1.Non-recursive 2.Recursive 3.Exit ********* Enter your choice 2 Element found at 1position Linear Search ********* 1.Non-recursive 2.Recursive 3.Exit ********* Enter your choice 3 */ b) Implementing both recursive and non-recursive functions using Binary search // BinarySearchRecursive.java public class BinarySearchRecursive { // need extra "helper" method, feed in params public int binarySearch(int[] a, int x) { return binarySearch(a, x, 0, a.length - 1); } // need extra low and high parameters private int binarySearch(int[ ] a, int x, int low, int high) { if (low > high) return -1; int mid = (low + high)/2; if (a[mid] == x) return mid; else if (a[mid] < x) return binarySearch(a, x, mid+1, high); else // last possibility: a[mid] > x return binarySearch(a, x, low, mid-1); } public static void main(String[] args) { Page 4 BinarySearchRecursive bin = new BinarySearchRecursive(); int[] a = { 2, 8,12,14,16,19,24,28,31,33,// 0-9 39,40,45,49,51,53,54,56,57,60,// 10-19 63,69,77,82,88,89,94,96,97}; // 20-28 for (int i = 0; i < a.length; i++) System.out.print(bin.binarySearch(a,a[i]) + " "); System.out.println(); System.out.print(bin.binarySearch(a,1) +" "); System.out.print(bin.binarySearch(a,26)+" "); System.out.print(bin.binarySearch(a,85)+" "); System.out.print(bin.binarySearch(a,99)+" "); System.out.print(bin.binarySearch(a,89)+" "); System.out.println(); } } /* Output: I:\M.Tech Lab\1 >java BinarySearchRecursive 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 -1 -1 -1 -1 25 */ // BinarySearch.java public class BinarySearch { // binarySeach: non-recursive public int binarySearch(int[] a, int x) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high)/2; if (a[mid] == x) return mid; else if (a[mid] < x) low = mid + 1; else high = mid - 1; } return -1; } public static void main(String[] args) { BinarySearch bin = new BinarySearch(); int[] a = { 2, 8,12,14,16,19,24,28,31,33,// 0-9 39,40,45,49,51,53,54,56,57,60,// 10-19 63,69,77,82,88,89,94,96,97}; // 20-28 Page 5 for (int i = 0; i < a.length; i++) System.out.print(bin.binarySearch(a,a[i]) + " "); System.out.println(); System.out.print(bin.binarySearch(a,1) +" "); System.out.print(bin.binarySearch(a,26)+" "); System.out.print(bin.binarySearch(a,85)+" "); System.out.print(bin.binarySearch(a,99)+" "); System.out.print(bin.binarySearch(a,89)+" "); System.out.println(); } } /* Output: I:\M.Tech Lab\1 >javac BinarySearch.java I:\M.Tech Lab\1 >java BinarySearch 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 -1 -1 -1 -1 25 */ 2) Write Java programs to implement the following using arrays and linked lists a) List ADT using Arrays //List.java public interface List { public void createList(int n); public void insertFirst(Object ob); public void insertAfter(Object ob, Object pos); public Object deleteFirst(); public Object deleteAfter(Object pos); public boolean isEmpty(); public int size(); } //ArrayList.java class ArrayList implements List { class Node { Object data; int next; Node(Object ob, int i) // constructor { data = ob; next = i; } } Page 6 int MAXSIZE; // max number of nodes in the list Node list[]; // create list array int head, count; // count: current number of nodes in the list ArrayList( int s) // constructor { MAXSIZE = s; list = new Node[MAXSIZE]; } public void initializeList() { for( int p = 0; p < MAXSIZE-1; p++ ) list[p] = new Node(null, p+1); list[MAXSIZE-1] = new Node(null, -1); } public void createList(int n) // create ‘n’ nodes { int p; for( p = 0; p < n; p++ ) { list[p] = new Node(11+11*p, p+1); count++; } list[p-1].next = -1; // end of the list } public void insertFirst(Object item) { if( count == MAXSIZE ) { System.out.println("***List is FULL"); return; } int p = getNode(); if( p != -1 ) { list[p].data = item; if( isEmpty() ) list[p].next = -1; else list[p].next = head; head = p; count++; } } public void insertAfter(Object item, Object x) { if( count == MAXSIZE ) { System.out.println("***List is FULL"); Page 7 return; } int q = getNode(); // get the available position to insert new node int p = find(x); // get the index (position) of the Object x if( q != -1 ) { list[q].data = item; list[q].next = list[p].next; list[p].next = q; count++; } } public int getNode() // returns available node index { for( int p = 0; p < MAXSIZE; p++ ) if(list[p].data == null) return p; return -1; } public int find(Object ob) // find the index (position) of the Object ob { int p = head; while( p != -1) { if( list[p].data == ob ) return p; p = list[p].next; // advance to next node } return -1; } public Object deleteFirst() { if( isEmpty() ) { System.out.println("List is empty: no deletion"); return null; } Object tmp = list[head].data; if( list[head].next == -1 ) // if the list contains one node, head = -1; // make list empty. else head = list[head].next; count--; // update count return tmp; } public Object deleteAfter(Object x) { Page 8 int p = find(x); if( p == -1 || list[p].next == -1 ) { System.out.println("No deletion"); return null; } int q = list[p].next; Object tmp = list[q].data; list[p].next = list[q].next; count--; return tmp; } public void display() { int p = head; System.out.print("\nList: [ " ); while( p != -1) { System.out.print(list[p].data + " "); // print data p = list[p].next; // advance to next node } System.out.println("]\n");// } public boolean isEmpty() { if(count == 0) return true; else return false; } public int size() { return count; } } // ArrayListMain.java class ArrayListMain { public static void main(String[] args) { ArrayList linkedList = new ArrayList(10); linkedList.initializeList(); linkedList.createList(4); // create 4 nodes linkedList.display(); // print the list System.out.print("InsertFirst 55:"); linkedList.insertFirst(55); Page 9 linkedList.display(); System.out.print("Insert 66 after 33:"); linkedList.insertAfter(66, 33); // insert 66 after 33 linkedList.display(); Object item = linkedList.deleteFirst(); System.out.println("Deleted node: " + item); linkedList.display(); System.out.print("InsertFirst 77:"); linkedList.insertFirst(77); linkedList.display(); item = linkedList.deleteAfter(22); // delete node after node 22 System.out.println("Deleted node: " + item); linkedList.display(); System.out.println("size(): " + linkedList.size()); } } /* Output: I:\M.Tech Lab\2\Array>javac ArrayListMain.java I:\M.Tech Lab\2\Array>java ArrayListMain List: [ 11 22 33 44 ] InsertFirst 55: List: [ 55 11 22 33 44 ] Insert 66 after 33: List: [ 55 11 22 33 66 44 ] Deleted node: 55 List: [ 11 22 33 66 44 ] InsertFirst 77: List: [ 77 11 22 33 66 44 ] Deleted node: 33 List: [ 77 11 22 66 44 ] size(): 5 */ Page 10 b) List ADT using Linked Lists //List.java public interface List { public void createList(int n); public void insertFirst(Object ob); public void insertAfter(Object ob, Object pos); public Object deleteFirst(); public Object deleteAfter(Object pos); public boolean isEmpty(); public int size(); } // LinkedList.java class LinkedList implements List { class Node { Object data; // data item Node next; // refers to next node in the list Node( Object d ) // constructor { data = d; } // ‘next’ is automatically set to null } Node head; // head refers to first node Node p; // p refers to current node int count; // current number of nodes public void createList(int n) // create 'n' nodes { p = new Node(11); // create first node head = p; // assign mem. address of 'p' to 'head' for( int i = 1; i < n; i++ ) // create 'n-1' nodes p = p.next = new Node(11 + 11*i); count = n; } public void insertFirst(Object item) // insert at the beginning of list { p = new Node(item); // create new node p.next = head; // new node refers to old head head = p; // new head refers to new node count++; } public void insertAfter(Object item,Object key) { p = find(key); // get "location of key item" Page 11 if( p == null ) System.out.println(key + " key is not found"); else { Node q = new Node(item); // create new node q.next = p.next; // new node next refers to p.next p.next = q; // p.next refers to new node count++; } } public Node find(Object key) { p = head; while( p != null ) // start at beginning of list until end of list { if( p.data == key ) return p; // if found, return key address p = p.next; // move to next node } return null; // if key search is unsuccessful, return null } public Object deleteFirst() // delete first node { if( isEmpty() ) { System.out.println("List is empty: no deletion"); return null; } Node tmp = head; // tmp saves reference to head head = tmp.next; count--; return tmp.data; } public Object deleteAfter(Object key) // delete node after key item { p = find(key); // p = "location of key node" if( p == null ) { System.out.println(key + " key is not found"); return null; } if( p.next == null ) // if(there is no node after key node) { System.out.println("No deletion"); return null; Page 12 } else { Node tmp = p.next; // save node after key node p.next = tmp.next; // point to next of node deleted count--; return tmp.data; // return deleted node } } public void displayList() { p = head; // assign mem. address of 'head' to 'p' System.out.print("\nLinked List: "); while( p != null ) // start at beginning of list until end of list { System.out.print(p.data + " -> "); // print data p = p.next; // move to next node } System.out.println(p); // prints 'null' } public boolean isEmpty() // true if list is empty { return (head == null); } public int size() { return count; } } // end of LinkeList class // LinkedListMain.java class LinkedListMain { public static void main(String[] args) { LinkedList list = new LinkedList(); // create list object list.createList(4); // create 4 nodes list.displayList(); list.insertFirst(55); // insert 55 as first node list.displayList(); list.insertAfter(66, 33); // insert 66 after 33 list.displayList(); Object item = list.deleteFirst(); // delete first node if( item != null ) { System.out.println("deleteFirst(): " + item); Page 13 list.displayList(); } item = list.deleteAfter(22); // delete a node after node(22) if( item != null ) { System.out.println("deleteAfter(22): " + item); list.displayList(); } System.out.println("size(): " + list.size()); } } /* Output: I:\M.Tech Lab\2\Linked Lists>java LinkedListMain Linked List: 11 -> 22 -> 33 -> 44 -> null Linked List: 55 -> 11 -> 22 -> 33 -> 44 -> null Linked List: 55 -> 11 -> 22 -> 33 -> 66 -> 44 -> null deleteFirst(): 55 Linked List: 11 -> 22 -> 33 -> 66 -> 44 -> null deleteAfter(22): 33 Linked List: 11 -> 22 -> 66 -> 44 -> null size(): 4 3) Write Java programs to implement the following using an array. a) Stack ADT b) Queue ADT a) Stack ADT using Array //Stack.java public interface Stack { public void push(Object ob); public Object pop(); public Object peek(); public boolean isEmpty(); public int size(); } // ArrayStack.java public class ArrayStack implements Stack { private Object a[]; private int top; //stack top Page 14 public ArrayStack(int n) { a = new Object[n]; // create stack array top = -1; //no item in the stack } public void push(Object item) //add an item on top of stack { if (top == a.length-1) { System.out.println("Stack is full"); return; } top++; //incerment top a[top] =item; //insert an item } public Object pop() //remove an item from top of stack { if(isEmpty()) { System.out.println("Stack is empty"); return null; } Object item = a[top]; // access top item top--; // decrement top return item; } public Object peek() // get top item of stack { if(isEmpty()) return null; return a[top]; } public boolean isEmpty() // true if stack is empty { return (top == -1); } public int size() //return number of items in the stack { return top+1; } } Page 15 // ArrayStackMain.java class ArrayStackMain { public static void main(String[] args) { ArrayStack stk = new ArrayStack(4); Object item; // push 3 items onto stack stk.push('A'); stk.push('B'); stk.push('C'); System.out.println("size(): " + stk. size()); //create stack of size 4 item = stk.pop(); // delete item System.out.println(item + "is deleted"); // add three more items to the stack stk.push('D'); stk.push('E'); stk.push('F'); System.out.println(stk.pop() + "is deleted"); // push one item stk.push('G'); // get top item from the stack item = stk.peek(); System.out.println(item + " is on top of stack"); }} /* Output: I:\M.Tech Lab\3 (a)>java ArrayStackMain size(): 3 Cis deleted Stack is full Eis deleted G is on top of stack */ b) Queue ADT using Array // Queue.java public interface Queue { public void insert(Object ob); public Object remove(); public Object peek(); public boolean isEmpty(); public int size(); Page 16 } // ArrayQueue.java class ArrayQueue implements Queue { private int maxSize; // maximum queue size private Object[] que; // que is an array private int front; private int rear; private int count; // count of items in queue (queue size) public ArrayQueue(int s) // constructor { maxSize = s; que = new Object[maxSize]; front = rear = -1; count = 0; } public void insert(Object item) // add item at rear of queue { if( count == maxSize ) { System.out.println("Queue is Full"); return; } if(rear == maxSize-1 || rear == -1) { que[0] = item; rear = 0; if( front == -1) front = 0; } else que[++rear] = item; count++; // update queue size } public Object remove() // delete item from front of queue { if( isEmpty() ) {System.out.println("Queue is Empty"); return 0; } Object tmp = que[front]; // save item to be deleted que[front] = null; // make deleted item’s cell empty if( front == rear ) rear = front = -1; else if( front == maxSize-1 ) front = 0; else front++; count--; // less one item from the queue size return tmp; } public Object peek() // peek at front of the queue { return que[front]; } public boolean isEmpty() // true if the queue is empty Page 17 { return (count == 0); } public int size() // current number of items in the queue { return count; } public void displayAll() { System.out.print("Queue: "); for( int i = 0; i < maxSize; i++ ) System.out.print( que[i] + " "); System.out.println(); } } // QueueMain.java class QueueMain { public static void main(String[] args) { /* queue holds a max of 5 items */ ArrayQueue q = new ArrayQueue(5); Object item; q.insert('A'); q.insert('B'); q.insert('C'); q.displayAll(); item = q.remove(); // delete item System.out.println(item + " is deleted"); item = q.remove(); System.out.println(item + " is deleted"); q.displayAll(); q.insert('D'); // insert 3 more items q.insert('E'); q.insert('F'); q.displayAll(); item = q.remove(); System.out.println(item + " is deleted"); q.displayAll(); System.out.println("peek(): " + q.peek()); q.insert('G'); q.displayAll(); System.out.println("Queue size: " + q.size()); } } /* Output: I:\M.Tech Lab\3 (b)>javac QueueMain.java I:\M.Tech Lab\3 (b)>java QueueMain Page 18 Queue: A B C null null A is deleted B is deleted Queue: null null C null null Queue: F null C D E C is deleted Queue: F null null D E peek(): D Queue: F G null D E Queue size: 4 */ 4) Write a Java program that reads an infix expression and converts the expression to postfix form (Use stack ADT). // InfixToPostfix.java class InfixToPostfix { java.util.Stack<Character> stk = new java.util.Stack<Character>(); public String toPostfix(String infix) { infix = "(" + infix + ")"; // enclose infix expr within parentheses String postfix = ""; /* scan the infix char-by-char until end of string is reached */ for( int i=0; i<infix.length(); i++) { char ch, item; ch = infix.charAt(i); if( isOperand(ch) ) // if(ch is an operand), then postfix = postfix + ch; // append ch to postfix string if( ch == '(' ) // if(ch is a left-bracket), then stk.push(ch); // push onto the stack if( isOperator(ch) ) // if(ch is an operator), then { item = stk.pop(); // pop an item from the stack /* if(item is an operator), then check the precedence of ch and item*/ if( isOperator(item) ) { if( precedence(item) >= precedence(ch) ) { stk.push(item); stk.push(ch); } else { postfix = postfix + item; stk.push(ch); } } else Page 19 { stk.push(item); stk.push(ch); } } // end of if(isOperator(ch)) if( ch == ')' ) { item = stk.pop(); while( item != '(' ) { postfix = postfix + item; item = stk.pop(); } } } // end of for-loop return postfix; } // end of toPostfix() method public boolean isOperand(char c) { return(c >= 'A' && c <= 'Z'); } public boolean isOperator(char c) { return( c=='+' || c=='-' || c=='*' || c=='/' ); } public int precedence(char c) { int rank = 1; // rank = 1 for '*’ or '/' if( c == '+' || c == '-' ) rank = 2; return rank; } } // InfixToPostfixMain.java class InfixToPostfixMain { public static void main(String args[]) { InfixToPostfix obj = new InfixToPostfix(); String infix = "A*(B+C/D)-E"; System.out.println("infix: " + infix ); System.out.println("postfix:"+obj.toPostfix(infix) ); } } /* I:\M.Tech Lab\4>java InfixToPostfixMain infix: A*(B+C/D)-E postfix:ABCD/+*E*/ Page 20 5) Write a Java program to implement circular queue ADT using an array // CirQue.java class CirQue { int front,rear,next=0; int que[]; int max,count=0; CirQue(int n) { max=n; que=new int[max]; front=rear=-1; } boolean isfull() { if(front==(rear+1)%max) return true; else return false; } boolean isempty() { if(front== -1&&rear== -1) return true; else return false; } int delete() { if(isempty()) { return -1; } else { count --; int x=que[front]; if(front==rear) front=rear= -1; else { next=(front+1)%max; front=next; } return x; } } void insert(int item) { if(isempty()) { Page 21 que[++rear]=item; front=rear; count ++; } else if(!isfull()) { next=(rear+1)%max; if(next!=front) { que[next]=item; rear=next; } count ++; } else System.out.println("q is full"); } void display() { if(isempty()) { System.out.println("queue is empty"); } else next=(front)%max; while(next<=rear) { System.out.println(que[next]); next++; } } int size() { return count; } } // CirQueMain.java import java.util.*; class CirQueMain { public static void main(String args[]) { int ch; Scanner s=new Scanner(System.in); System.out.println("enter limit"); int n=s.nextInt(); CirQue q=new CirQue(n); do { System.out.println("1.insert"); System.out.println("2.delete"); Page 22 System.out.println("3.display"); System.out.println("4.size"); System.out.println("enter ur choice :"); System.out.println("**************"); ch=s.nextInt(); switch(ch) { case 1:System.out.println("enter element :"); int n1=s.nextInt(); q.insert(n1); break; case 2:int c1=q.delete(); if(c1>0) System.out.println("deleted element is :"+c1); else System.out. println("can't delete"); break; case 3:q.display(); break; case 4:System.out.println("queue size is "+q.size()); break; } } while(ch!=0); } } /* Output: I:\M.Tech Lab\5>javac CirQueMain.java I:\M.Tech Lab\5>java CirQueMain enter limit 4 1.insert 2.delete 3.display 4.size enter ur choice : ************** 1 enter element : 25 1.insert 2.delete 3.display 4.size enter ur choice : ************** 1 enter element : 33 Page 23 1.insert 2.delete 3.display 4.size enter ur choice : ************** 1 enter element : 45 1.insert 2.delete 3.display 4.size enter ur choice : ************** 1 enter element : 55 1.insert 2.delete 3.display 4.size enter ur choice : ************** 1 enter element : 66 q is full 1.insert 2.delete 3.display 4.size enter ur choice : ************** 3 25 33 45 55 1.insert 2.delete 3.display 4.size enter ur choice : ************** 3 25 33 45 55 1.insert Page 24 2.delete 3.display 4.size enter ur choice : ************** 4 queue size is 4 1.insert 2.delete 3.display 4.size enter ur choice : ************** 2 deleted element is :25 1.insert 2.delete 3.display 4.size enter ur choice : ************** 3 33 45 55 1.insert 2.delete 3.display 4.size enter ur choice : ************** 4 queue size is 3 1.insert 2.delete 3.display 4.size enter ur choice : ************** 1 enter element : 58 1.insert 2.delete 3.display 4.size enter ur choice : ************** 3 1.insert 2.delete Page 25 3.display 4.size enter ur choice : ************** 2 deleted element is :33 1.insert 2.delete 3.display 4.size enter ur choice : ************** 3 1.insert 2.delete 3.display 4.size enter ur choice : ************** 4 queue size is 3 1.insert 2.delete 3.display 4.size enter ur choice : ************** 3 1.insert 2.delete 3.display 4.size enter ur choice : ************** 2 deleted element is :45 1.insert 2.delete 3.display 4.size enter ur choice : ************** 3 1.insert 2.delete 3.display 4.size enter ur choice : ************** 3 */ Page 26 6) Write a Java program that uses both a stack and a queue to test whether the given string is a Palindrome or not. // Node.java class Node { char data; Node next; Node() { this(' '); } Node(char data) { this.data=data; next=null; } Node(char data,Node next) { this.data=data; this.next=next; } } // Stack.java class Stack { Node top; boolean isEmpty() { if(top==null) return true; return false; } void push(char item) { Node nn=new Node(item,top); top=nn; } char pop() { if(top!=null) { char k=top.data; top=top.next; return k; } else System.out.println("Stack is Empty"); return '#'; } } Page 27 // Que.java class Que { Node front,rear; boolean isEmpty() { if(front==null) return true; return false; } void enqueue(char item) { Node nn=new Node(item); if(isEmpty()) front=rear=nn; else { rear.next=nn; rear=nn; } } char delqueue() { char k=' '; if(isEmpty()) System.out.println("Cannot delete,Queue is empty"); else if(front==rear) { k=front.data; front=rear=null; } else { k=front.data; front=front.next; } return k; } } // Palindrome.java import java.io.*; class Palindrome { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Stack st=new Stack(); Que q=new Que(); System.out.println("Enter any string to check whether PALINDROME OR NOT"); String str=br.readLine(); Page 28 int i,flag=0,l=str.length(); char ch1,ch2; for(i=0;i<l/2;i++) st.push(str.charAt(i)); i=(l+1)/2; while(i<l) { q.enqueue(str.charAt(i)); i++; } for(i=0;i<l/2;i++) if(st.pop()!=q.delqueue()) { flag=1; break; } if(flag==0) System.out.println("\n"+str+" is a PALINDROME"); else System.out.println("\n"+str+" is NOT A PALINDROME"); } } /* Output: I:\M.Tech Lab\6\New Folder>java Palindrome Enter any string to check whether PALINDROME OR NOT RADAR RADAR is a PALINDROME I:\M.Tech Lab\6\New Folder>java Palindrome Enter any string to check whether PALINDROME OR NOT india india is NOT A PALINDROME */ 7) Write Java programs to implement the following using a singly linked list. a) Stack ADT b) Queue ADT a) Stack ADT using singly linked list // Node.java class Node { int data; // data item Node next; // next node in linked-stack Node( int d ) // constructor { data = d; } // next is automatically set to null } // LinkedStack.java class LinkedStack { Page 29 Node top; // top refers to top-node Node p; // p refers to current node public void push(int item) // add item onto stack { p = new Node(item); // create new node p.next = top; // new node refers to old top top = p; // top refers to new node } public Node pop() // remove a node from the stack { if( isEmpty() ) { System.out.println("Stack is empty"); return null; } Node tmp = top; // tmp saves reference to top node top = tmp.next; // now, top refers to next node of old top return tmp; // return the popped item } public Node peek() // get top node from the stack, without deleting { if( isEmpty() ) { System.out.println("Stack is empty"); return null; } return top; } public void displayStack() { p = top; // p refers to top System.out.print("\nContents of Stack: [ "); while( p != null ) // start printing from top of stack to bottom of stack { System.out.print(p.data + " "); // print data p = p.next; // move to next node } System.out.println("]"); } public boolean isEmpty() // true if stack is empty { return (top == null); } } // LinkedStackMain.java class LinkedStackMain { public static void main(String[] args) { LinkedStack stk = new LinkedStack(); // create stack object Node item; // item stores popped node stk.push(20); // add 20, 35, 40 to stack Page 30 stk.push(35); stk.push(40); stk.displayStack(); // print contents of stack item = stk.pop(); // remove a node from the top and print it if( item != null ) { System.out.println("Popped item: " + item.data); stk.displayStack(); } stk.push(65); // insert 65, 70, 75 stk.push(70); stk.push(75); stk.displayStack(); // display contents of stack item = stk.pop(); // remove a node from the top and display it if( item != null ) { System.out.println("Popped item: " + item.data); stk.displayStack(); } System.out.println("peek(): " + stk.peek());// get top item stk.push(90); // insert 90 stk.displayStack(); } } /* Output: I:\M.Tech Lab\7 (a)>java LinkedStackMain Contents of Stack: [ 40 35 20 ] Popped item: 40 Contents of Stack: [ 35 20 ] Contents of Stack: [ 75 70 65 35 20 ] Popped item: 75 Contents of Stack: [ 70 65 35 20 ] peek(): Node@b162d5 Contents of Stack: [ 90 70 65 35 20 ] */ b) Queue ADT using singly linked list // LinkedQueue.java public class LinkedQueue { class Node { Object data; Node next; Node(Object item) // constructor { Page 31 data = item; } } Node front, rear; int count; public void insert(Object item) { Node p = new Node(item); if(front == null) // queue is empty; insert first item { front = rear = p; rear.next = null; } if(front == rear) // queue contains one item; insert second item { rear = p; front.next = rear; rear.next = null; } else // queue contains 2 or more items { rear.next = p; // old rear.next refers to p rear = p; // new rear refers to p rear.next = null; } count++; // increment queue size } public Object remove() { if(isEmpty()) { System.out.println("Q is empty"); return null; } Object item = front.data; front = front.next; count--; // decrement queue size return item; } public boolean isEmpty() { return (front == null); } public Object peek() { return front.data; } public int size() { return count; } public void display() { Node p = front; System.out.print("Linked Q: "); if(p == null) System.out.println("empty"); while( p != null ) { System.out.print(p.data + " "); p = p.next; } System.out.println(); } } Page 32 // LinkedQueueMain.java class LinkedQueueMain { public static void main(String[] args) { LinkedQueue q = new LinkedQueue(); q.display(); q.insert('A'); q.insert('B'); q.insert('C'); q.insert('D'); q.display(); System.out.println("delete(): " + q.remove()); q.display(); System.out.println("peek(): " + q.peek()); q.insert('E'); q.insert('F'); System.out.println("delete(): " + q.remove()); q.display(); System.out.println("size(): " + q.size()); } } /* Output: I:\M.Tech Lab\7 (b)>java LinkedQueueMain Linked Q: empty Linked Q: A B C D delete(): A Linked Q: B C D peek(): B delete(): B Linked Q: C D E F size(): 4 */ 8) Write Java programs to implement the deque (double ended queue) ADT using a) Array b) Singly linked list c) Doubly linked list. //ArrayDeque.java public class ArrayDeque { private int maxSize; private Object[] que; private int first; private int last; private int count; // current number of items in deque public ArrayDeque(int s) // constructor { maxSize = s; que = new Object[maxSize]; first = last = -1; count = 0; } Page 33 public void addLast(Object item) { if(count == maxSize) { System.out.println("Deque is full"); return; } last = (last+1) % maxSize; que[last] = item; if(first == -1 && last == 0) first = 0; count++; } public Object removeLast() { if(count == 0) { System.out.println("Deque is empty"); return(' ');} Object item = que[last]; que[last] = ' '; if(last > 0) last = (last-1) % maxSize; count--; if(count == 0) first = last = -1; return(item); } public void addFirst(Object item) { if(count == maxSize) { System.out.println("Deque is full"); return; } if(first > 0) first = (first-1) % maxSize; else if(first == 0) first = maxSize-1; que[first] = item; count++; } public Object removeFirst() { if(count == 0) { System.out.println("Deque is empty"); return(' '); } Object item = que[first]; que[first] = ' '; if(first == maxSize-1) first = 0; else first = (first+1) % maxSize; count--; if(count == 0) first = last = -1; return(item); } void display() { System.out.println("----------------------------"); Page 34 System.out.print("first:"+first + ", last:"+ last); System.out.println(", count: " + count); System.out.println(" 0 1 2 3 4 5"); System.out.print("Deque: "); for( int i=0; i<maxSize; i++ ) System.out.print(que[i]+ " "); System.out.println("\n----------------------------"); } public boolean isEmpty() // true if queue is empty { return (count == 0); } public boolean isFull() // true if queue is full { return (count == maxSize); } } // ArrayDequeMain class ArrayDequeMain { public static void main(String[] args) { ArrayDeque q = new ArrayDeque(6); // queue holds a max of 6 items q.insertLast('A'); /* (a) */ q.insertLast('B'); q.insertLast('C'); q.insertLast('D'); System.out.println("deleteFirst():"+q.deleteFirst()); q.display(); q.insertLast('E'); /* (b) */ q.display();/* (c) */ System.out.println("deleteLast():"+q.deleteLast()); System.out.println("deleteLast():"+q.deleteLast()); q.display(); q.insertFirst('P'); q.insertFirst('Q'); /* (d) */ q.insertFirst('R'); q.display(); q.deleteFirst(); q.display(); /* (e) */ q.insertFirst('X'); q.display(); /* (f) */ q.insertLast('Y'); q.display(); /* (g) */ q.insertLast('Z'); q.display(); /* (h) */ } } /* Output: deleteFirst(): A ---------------------------first:1, last:3, count: 3 012345 Deque: B C D ---------------------------first:1, last:4, count: 4 012345 Deque: B C D E Page 35 ---------------------------deleteLast(): E deleteLast(): D ---------------------------first:1, last:2, count: 2 012345 Deque: B C ---------------------------first:4, last:2, count: 5 012345 Deque: P B C R Q ---------------------------first:5, last:2, count: 4 012345 Deque: P B C Q ---------------------------first:4, last:2, count: 5 012345 Deque: P B C X Q ---------------------------first:4, last:3, count: 6 012345 Deque: P B C Y X Q ---------------------------Deque is full ---------------------------first:4, last:3, count: 6 012345 Deque: P B C Y X Q ---------------------------*/ b) Doubly linked list. // LinkedDeque public class LinkedDeque { public class DequeNode { DequeNode prev; Object data; DequeNode next; DequeNode( Object item ) // constructor { data = item; } // prev & next automatically refer to null } private DequeNode first, last; private int count; public void addFirst(Object item) { if( isEmpty() ) first = last = new DequeNode(item); else Page 36 { DequeNode tmp = new DequeNode(item); tmp.next = first; first.prev = tmp; first = tmp; } count++; } public void addLast(Object item) { if( isEmpty() ) first = last = new DequeNode(item); else { DequeNode tmp = new DequeNode(item); tmp.prev = last; last.next = tmp; last = tmp; } count++; } public Object removeFirst() { if( isEmpty() ) { System.out.println("Deque is empty"); return null; } else { Object item = first.data; first = first.next; first.prev = null; count--; return item; } } public Object removeLast() { if( isEmpty() ) { System.out.println("Deque is empty"); return null; } else { Object item = last.data; last = last.prev; last.next = null; count--; return item; } } public Object getFirst() { if( !isEmpty() ) return( first.data ); else return null; Page 37 } public Object getLast() { if( !isEmpty() ) return( last.data ); else return null; } public boolean isEmpty() { return (count == 0); } public int size() { return(count); } public void display() { DequeNode p = first; System.out.print("Deque: [ "); while( p != null ) { System.out.print( p.data + " " ); p = p.next; } System.out.println("]"); } } // LinkedDequeMain public class LinkedDequeMain { public static void main( String args[]) { LinkedDeque dq = new LinkedDeque(); System.out.println("removeFirst():" + dq.removeFirst()); dq.addFirst('A'); dq.addFirst('B'); dq.addFirst('C'); dq.display(); dq.addLast('D'); dq.addLast('E'); System.out.println("getFirst():" + dq.getFirst()); System.out.println("getLast():" + dq.getLast()); dq.display(); System.out.println("removeFirst():"+dq.removeFirst()); System.out.println("removeLast():"+ dq.removeLast()); dq.display(); System.out.println("size():" + dq.size()); } } /* Output: I:\M.Tech Lab\8 (c)>java LinkedDequeMain Deque is empty removeFirst():null Deque: [ C B A ] getFirst():C getLast():E Deque: [ C B A D E ] Page 38 removeFirst():C removeLast():E Deque: [ B A D ] size():3 */ 9) Write a Java program to implement priority queue ADT //Node.java public class Node { String data; // data item int prn; // priority number (minimum has highest priority) Node next; // "next" refers to the next node Node(String str, int p) // constructor { data = str; prn = p; } // "next" is automatically set to null } // LinkedPriorityQueue class LinkedPriorityQueue { Node head; // head refers to first node public void insert(String item, int pkey) // insert item after pkey { Node newNode = new Node(item, pkey); // create new node int k; if( head == null ) k = 1; else if( newNode.prn < head.prn ) k = 2; else k = 3; switch( k ) { case 1: head = newNode; // Q is empty, add head node head.next = null; break; case 2: Node oldHead = head; // add one item before head head = newNode; newNode.next = oldHead; break; case 3: Node p = head; // add item before a node Node prev = p; Node nodeBefore = null; while( p != null ) { if( newNode.prn < p.prn ) { nodeBefore = p; break; } else { prev = p; // save previous node of current node p = p.next; // move to next node Page 39 } } // end of while newNode.next = nodeBefore; prev.next = newNode; } // end of switch } // end of insert() method public Node delete() { if( isEmpty() ) { System.out.println("Queue is empty"); return null; } else { Node tmp = head; head = head.next; return tmp; } } public void displayList() { Node p = head; // assign address of head to p System.out.print("\nQueue: "); while( p != null ) // start at beginning of list until end of list { System.out.print(p.data+"(" +p.prn+ ")" + " "); p = p.next; // move to next node } System.out.println(); } public boolean isEmpty() // true if list is empty { return (head == null); } public Node peek() // get first item { return head; } } // LinkedPriorityQueueMain class LinkedPriorityQueueMain { public static void main(String[] args) { LinkedPriorityQueue pq = new LinkedPriorityQueue(); // create new queue list Node item; pq.insert("kumar", 3); pq.insert("anil", 2); pq.insert("Kishore", 2); pq.insert("Ravi", 1); pq.insert("Siva", 3); Page 40 pq.displayList(); item = pq.delete(); if( item != null ) System.out.println("delete():" + item.data + "(" +item.prn+")"); pq.displayList(); pq.insert("Arnold", 2); pq.insert("Neeru", 1); pq.insert("Hasini", 4); pq.displayList(); } } /* Output: I:\M.Tech Lab\9>java LinkedPriorityQueueMain Queue: Ravi(1) anil(2) Kishore(2) kumar(3) Siva(3) delete():Ravi(1) Queue: anil(2) Kishore(2) kumar(3) Siva(3) Queue: Neeru(1) anil(2) Kishore(2) Arnold(2) kumar(3) Siva(3) Hasini(4) */ 10) Write a Java program to perform the following operations: a) Construct a binary search tree of elements. b) Search for a key element in the above binary search tree. c) Delete an element from the above binary search tree. // Bstnode.java import java.util.*; class Bstnode { Bstnode rc,lc; Bstnode root; int data; Bstnode () { data=0; rc=lc=null; } Bstnode(int item) { data=item; lc=rc=null; } Bstnode[] search(int key) { Bstnode par ,ptr; Bstnode b[]=new Bstnode[2]; Page 41 ptr=root; par=null; while(ptr!=null) { if(ptr.data==key) { b[0]=par; b[1]=ptr; return b; } else if(ptr.data<key) { par=ptr; ptr=ptr.rc; } else { par=ptr; ptr=ptr.lc; } } b[0]=par;b[1]=ptr; return b; } void insert(int item) { Bstnode arr[]=new Bstnode[2]; Bstnode nn=new Bstnode(item); arr=search(item); if(root!=null) { Bstnode par=arr[0]; Bstnode ptr=arr[1]; if(ptr!=null) System.out.println("key already existed"); else { if(par.data<item) par.rc=nn; else par.lc=nn; } } else root=nn; } void inorder(Bstnode ptr) { if(ptr!=null) { Page 42 inorder(ptr.lc); System.out.println(ptr.data); inorder(ptr.rc); } } void preorder(Bstnode ptr) { if(ptr!=null) { System.out.println(ptr.data); inorder(ptr.lc); inorder(ptr.rc); } } void postorder(Bstnode ptr) { if(ptr!=null) { inorder(ptr.lc); inorder(ptr.rc); System.out.println(ptr.data); } } int deleteleaf(Bstnode par,Bstnode ptr) { if(par!=null) { if(par.lc==ptr) par.lc=null; else par.rc=null; } else root=null; return ptr.data; } int delete1childnode(Bstnode par,Bstnode ptr) { if(par!=null) { if(par.lc==ptr) { if(ptr.lc==null) par.lc=ptr.rc; else par.lc=ptr.lc; } else if(par.rc==ptr) { if(ptr.lc==null) par.rc=ptr.rc; Page 43 else par.rc=ptr.lc; } } else { if(ptr.rc!=null) root=ptr.rc; else root=ptr.lc; } return ptr.data; } int delete2childnode(Bstnode par,Bstnode ptr) { Bstnode ptr1=ptr.rc; Bstnode par1=null; while(ptr1.lc!=null) { par1=ptr1; ptr1=ptr1.lc; } if(par1!=null) { if(ptr1.rc!=null) par1.lc=ptr1.rc; else par1.lc=null; ptr1.lc=ptr.lc; ptr1.rc=ptr.rc; } else // if par1=null ptr1.lc = ptr.lc; if(par!=null) { if(par.lc==ptr) par.lc=ptr1; else par.rc=ptr1; } else root=ptr1; return ptr.data; } int deletenode(int item) { Bstnode ptr=root,par=null; boolean flag=false; int k; while(ptr!=null&&flag==false) Page 44 { if(item<ptr.data) { par=ptr; ptr=ptr.lc; } else if(item>ptr.data) { par=ptr; ptr=ptr.rc; } else { ptr.data=item; flag=true; } } if(flag==false) { System. out.println("item not found hence can not delete"); return -1; } if(ptr.lc==null&&ptr.rc==null) k=deleteleaf(par,ptr); else if(ptr.lc!=null&&ptr.rc!=null) k=delete2childnode(par,ptr); else k=delete1childnode(par,ptr); return k; } public static void main(String saichandra[]) { Bstnode b=new Bstnode(); Scanner s=new Scanner (System.in); int ch; do { System.out.println("1.insert"); System.out.println("2.delete"); System.out.println("3.search"); System.out.println("4.inorder"); System.out.println("5.preorder"); System.out.println("6.postorder"); System.out.print("enter ur choice:"); ch=s.nextInt(); switch(ch) { case 1:System.out.print("enter element:"); int n=s.nextInt(); Page 45 b.insert(n); break; case 2:if(b.root!=null) { System.out.print("enter element:"); int n1=s.nextInt(); int res=b.deletenode(n1); if(res!=-1) System.out.println("deleted element is:"+res); } else System.out.println("no elements in tree"); break; case 3:if(b.root!=null) { System.out.println("enter search element"); int key=s.nextInt(); Bstnode search1[]=new Bstnode[2]; search1=b.search(key); if(search1[1]!=null) System.out.println("key is found"); else System.out.println("key not found"); if(search1[0]!=null) { if(search1[1]!=null) System.out.println("parent of the searched element is:"+search1[0].data); } else System.out.println("key is root no parent exist"); } else System.out.println("no elements in tree"); break; case 4:if(b.root!=null) b.inorder(b.root); else System.out.println("no elements in tree"); break; case 5:if(b.root!=null) b.preorder(b.root); else System.out.println("no elements in tree"); break; case 6:if(b.root!=null) b.postorder(b.root); else System.out.println("no elements in tree"); break; } } Page 46 while(ch!=0); } } /* Output: I:\M.Tech Lab\10>java Bstnode 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice:1 enter element:25 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice:1 enter element:35 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice:1 enter element:45 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice:3 enter search element 26 key not found 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice:3 enter search element 25 key is found Page 47 key is root no parent exist 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice:2 enter element:45 deleted element is:45 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice:3 enter search element 45 key not found 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice:3 enter search element 35 key is found parent of the searched element is:25 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice:4 25 35 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice:5 25 35 1.insert 2.delete Page 48 3.search 4.inorder 5.preorder 6.postorder enter ur choice:6 35 25 1.insert 2.delete 3.search 4.inorder 5.preorder 6.postorder enter ur choice: */ 11) Write a Java program to implement all the functions of a dictionary (ADT) using Hashing. // Hash.java class Hash { int item,size; int hArray[]; static int cnt; Hash(int n) { size=n; hArray=new int[size]; for(int i=0;i<size;i++) hArray[i]=-99; } int Hashfun(int key) { key=key%7; return key; } void insert(int key) { if(cnt>=size) System.out.println("insertion failed as array full....................!"); else { int hvalue=Hashfun(key);int j=1; while(hArray[hvalue]!=-99) { hvalue=hvalue+(j*j); //Quadratic probing hvalue=hvalue%size; j++; } hArray[hvalue]=key; cnt++; Page 49 } } int search(int key) { int searchval=Hashfun(key);int j=1; while(hArray[searchval]!=-99) { if(hArray[searchval]==key) return searchval; searchval=searchval+(j*j); searchval=searchval%size; j++; } return-1; } int delete(int key) { int delkey=search(key); if(delkey==-1) { System.out.println("deletion failed as key not found"); return-1; } else { hArray[delkey]=-99; return key; } } void display() { for(int j=0;j<size;j++) { System.out.println(j+": "+hArray[j]+"\n"); } } } // HashMain.java import java.util.*; import java.io.*; class HashMain { public static void main(String args[])throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter array size:"); int size=Integer.parseInt(br.readLine()); int ch; Hash h=new Hash(size); do { Page 50 System.out.println("1.insert\n2.display\n3.search\n4.delete"); System.out.println("enter choice:"); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1:int n=Integer.parseInt(br.readLine()); h.insert(n); break; case 2: h.display(); break; case 3: int find=Integer.parseInt(br.readLine()); int r= h.search(find); if(r!=-1) System.out.println("element is found at:"+r+" index"); else System.out.println("element is not found"); break; case 4: int key=Integer.parseInt(br.readLine()); int dr= h.delete(key); if(dr!=-1) System.out.println(dr+" is deleted"); h.display(); break; } }while(ch!=0); } } /* Output: I:\M.Tech Lab\11>javac HashMain.java I:\M.Tech Lab\11>java HashMain enter array size: 9 1.insert 2.display 3.search 4.delete enter choice: 1 23 1.insert 2.display 3.search 4.delete enter choice: 1 30 1.insert 2.display 3.search Page 51 4.delete enter choice: 1 56 1.insert 2.display 3.search 4.delete enter choice: 1 49 1.insert 2.display 3.search 4.delete enter choice: 1 48 1.insert 2.display 3.search 4.delete enter choice: 1 12 1.insert 2.display 3.search 4.delete enter choice: 1 65 1.insert 2.display 3.search 4.delete enter choice: 1 75 1.insert 2.display 3.search 4.delete enter choice: 2 0: 56 1: 49 2: 23 Page 52 3: 30 4: -99 5: 12 6: 48 7: 65 8: 75 1.insert 2.display 3.search 4.delete enter choice: 3 12 element is found at:5 index 1.insert 2.display 3.search 4.delete enter choice: 4 48 48 is deleted 0: 56 1: 49 2: 23 3: 30 4: -99 5: 12 6: -99 7: 65 8: 75 1.insert 2.display 3.search 4.delete enter choice: */ Page 53 12) Write a Java program to implement Dijkstra’s algorithm for Single source shortest path problem. // DijkstraAlgorithmSet.java import java.util.HashSet; import java.util.InputMismatchException; import java.util.Iterator; import java.util.Scanner; import java.util.Set; public class DijkstraAlgorithmSet { private int distances[]; private Set<Integer> settled; private Set<Integer> unsettled; private int number_of_nodes; private int adjacencyMatrix[][]; public DijkstraAlgorithmSet(int number_of_nodes) { this.number_of_nodes = number_of_nodes; distances = new int[number_of_nodes + 1]; settled = new HashSet<Integer>(); unsettled = new HashSet<Integer>(); adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1]; } public void dijkstra_algorithm(int adjacency_matrix[][], int source) { int evaluationNode; for (int i = 1; i <= number_of_nodes; i++) for (int j = 1; j <= number_of_nodes; j++) { adjacencyMatrix[i][j] = adjacency_matrix[i][j]; for (int i = 1; i <= number_of_nodes; i++) distances[i] = Integer.MAX_VALUE; } unsettled.add(source); distances[source] = 0; while (!unsettled.isEmpty()) { evaluationNode = getNodeWithMinimumDistanceFromUnsettled(); unsettled.remove(evaluationNode); settled.add(evaluationNode); evaluateNeighbours(evaluationNode); } } private int getNodeWithMinimumDistanceFromUnsettled() Page 54 { int min ; int node = 0; Iterator<Integer> iterator = unsettled.iterator(); node = iterator.next(); min = distances[node]; for (int i = 1; i <= distances.length; i++) { if (unsettled.contains(i)) { if (distances[i] <= min) { min = distances[i]; node = i; } } } return node; } private void evaluateNeighbours(int evaluationNode) { int edgeDistance = -1; int newDistance = -1; for (int destinationNode = 1; destinationNode <= number_of_nodes; destinationNode++) { if (!settled.contains(destinationNode)) { if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE) { edgeDistance = adjacencyMatrix[evaluationNode][destinationNode]; newDistance = distances[evaluationNode] + edgeDistance; } } } if (newDistance < distances[destinationNode]) { distances[destinationNode] = newDistance; } unsettled.add(destinationNode); } public static void main(String... arg) { int adjacency_matrix[][]; int number_of_vertices; int source = 0; Scanner scan = new Scanner(System.in); Page 55 try { System.out.println("Enter the number of vertices"); number_of_vertices = scan.nextInt(); adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1]; System.out.println("Enter the Weighted Matrix for the graph"); for (int i = 1; i <= number_of_vertices; i++) { for (int j = 1; j <= number_of_vertices; j++) { adjacency_matrix[i][j] = scan.nextInt(); if (i == j) { adjacency_matrix[i][j] = 0; continue; } if (adjacency_matrix[i][j] == 0) { adjacency_matrix[i][j] = Integer.MAX_VALUE; } } } System.out.println("Enter the source "); source = scan.nextInt(); DijkstraAlgorithmSet dijkstrasAlgorithm = new DijkstraAlgorithmSet(number_of_vertices); dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix, source); System.out.println("The Shorted Path to all nodes are "); for (int i = 1; i <= dijkstrasAlgorithm.distances.length - 1; i++) { System.out.println(source + " to " + i + " is "+ dijkstrasAlgorithm.distances[i]); } } { } catch (InputMismatchException inputMismatch) System.out.println("Wrong Input Format"); } scan.close(); } /* Output: I:\M.Tech Lab\12>javac DijkstraAlgorithmSet.java I:\M.Tech Lab\12>java DijkstraAlgorithmSet Enter the number of vertices 5 Enter the Weighted Matrix for the graph 09653 00000 Page 56 02040 00000 00000 Enter the source 1 The Shorted Path to all nodes are 1 to 1 is 0 1 to 2 is 8 1 to 3 is 6 1 to 4 is 5 1 to 5 is 3 */ 13) Write Java programs that use recursive and non-recursive functions to traverse the given binary tree in a) Preorder b) Inorder c) Postorder. // Traversals.java import java.util.*; class Traversals { Traversals rc,lc; static Traversals root; int data; Traversals a[]=new Traversals[100]; int top= -1; Traversals() { data=0; rc=lc=null; } Traversals(int item) { data=item; lc=rc=null; } Traversals[] search(int key) { Traversals par ,ptr; Traversals b[]=new Traversals[2]; ptr=root; par=null; while(ptr!=null) { if(ptr.data==key) { b[0]=par; b[1]=ptr; return b; } else if(ptr.data<key) { par=ptr; Page 57 ptr=ptr.rc; } else { par=ptr; ptr=ptr.lc; } } b[0]=par; b[1]=ptr; return b; } void insert(int item) { Traversals arr[]=new Traversals[2]; Traversals nn=new Traversals(item); arr=search(item); if(root!=null) { Traversals par=arr[0]; Traversals ptr=arr[1]; if(ptr!=null) System.out.println("key already existed"); else { if(par.data<item) par.rc=nn; else par.lc=nn; } } else root=nn; } void push(Traversals item) { a[++top]=item; } Traversals pop() { return a[top--]; } void preorder(Traversals root) { Traversals ptr=root; if(ptr!=null) push(ptr); while(top!= -1) { ptr=pop(); if(ptr!=null) Page 58 { System.out.println(ptr.data); push(ptr.rc); push(ptr.lc); } } } void inorder(Traversals root) { int count=0,count1=0,count2=0; Traversals ptr; ptr=root; while(top!= -1||ptr!=null) { if(ptr!=null) { push(ptr); ptr=ptr.lc; } else { ptr=pop(); int k=counting(ptr); if(k==0)count++; else if(k==1)count1++; else if(k==2)count2++; System.out.println(ptr.data); ptr=ptr.rc; } } System.out.println("2 child nodes:"+count2); System.out.println("1 child nodes:"+count1); System.out.println("leaf nodes:"+count); } void postorder(Traversals root) { Traversals ptr=root; int f1[]=new int[20]; int i= -1,flag; do { while(ptr!=null) { push(ptr); i++; f1[i]=0; if(ptr.rc!=null) { push(ptr.rc); i++; f1[i]=1; Page 59 } ptr=ptr.lc; } flag=f1[i]; i--; ptr=pop(); while(flag==0) { System.out.println(ptr.data); ptr=pop(); flag=f1[i]; i--; } if(flag==1) flag=0; }while(true); } int counting(Traversals ptr) { if(ptr.lc!=null&& ptr.rc!=null){return 2;} else if(ptr.lc!=null||ptr.rc!=null){return 1;} else return 0; } public static void main(String st[]) { Traversals b=new Traversals(); Scanner s=new Scanner (System.in); int ch; do { System.out.println("1.insert"); System.out.println("3.search"); System.out.println("4.preorder"); System.out.println("5.inorder"); System.out.println("6.postorder \n7.counting"); System.out.print("enter ur choice:"); ch=s.nextInt(); switch(ch) { case 1:System.out.print("enter element:"); int n=s.nextInt(); b.insert(n); break; case 3:if(root!=null) { System.out.println("enter search element"); int key=s.nextInt(); Traversals search1[]=new Traversals[2]; search1=b.search(key); if(search1[1]!=null) Page 60 System.out.println("key is found"); else System.out.println("key not found"); if(search1[0]!=null) { if(search1[1]!=null) System.out.println("parent of the searched element is:"+search1[0].data); } else System.out.println("key is root no parent exist"); } else System.out.println("no elements in tree"); break; case 4:if(root!=null) b.preorder(root); else System.out.println("no elements in tree"); break; case 5:if(root!=null) b.inorder(root); else System.out.println("no elements in tree"); break; case 6:if(root!=null) b.postorder(root); else System.out.println("no elements in tree"); break; case 7: break; } }while(ch!=0); } } /* Output: I:\M.Tech Lab\13>java Traversals 1.insert 3.search 4.preorder 5.inorder 6.postorder 7.counting enter ur choice:1 enter element:12 1.insert 3.search 4.preorder 5.inorder 6.postorder Page 61 7.counting enter ur choice:1 enter element:15 1.insert 3.search 4.preorder 5.inorder 6.postorder 7.counting enter ur choice:1 enter element:25 1.insert 3.search 4.preorder 5.inorder 6.postorder 7.counting enter ur choice:1 enter element:35 1.insert 3.search 4.preorder 5.inorder 6.postorder 7.counting enter ur choice:3 enter search element 15 key is found parent of the searched element i 1.insert 3.search 4.preorder 5.inorder 6.postorder 7.counting enter ur choice:4 12 15 25 35 1.insert 3.search 4.preorder 5.inorder 6.postorder 7.counting enter ur choice:5 12 15 25 Page 62 35 2 child nodes:0 1 child nodes:3 leaf nodes:1 1.insert 3.search 4.preorder 5.inorder 6.postorder 7.counting enter ur choice: */ 14) Write Java programs for the implementation of bfs and dfs for a given graph. // stack.java class stack { int top,size; String ele,s[]; stack(int n) { s=new String[n]; top= -1; } void push(String x) { ele=x; s[++top]=ele; } void pop() { if(!isempty()) top --; } boolean isempty() { if(top== -1) return true; else return false; } String peek() { return s[top]; } } // queue.java class queue { int front,rear; String que[]; int max,count=0; Page 63 queue(int n) { max=n; que=new String[max]; front=rear= -1; } boolean isfull() { if(rear==(max-1)) return true; else return false; } boolean isempty() { if(front== -1) return true; else return false; } void insert(String n) { if(isfull()) System.out.println("list is full"); else { rear++; que[rear]=n; if(front==-1) front=0; count++; } } String delete() { String x; if(isempty()) return null; else { x=que[front]; que[front]=null; if(front==rear) front=rear= -1; else front++; count --; } return x; } } Page 64 // Graph1.java class Graph1 { String ver[]=new String[20]; static int nverts; static int size; int a[][]; Graph1() { int max=50; a=new int[max][max]; for(int i=0;i<max;i++) for(int j=0;j<max;j++) a[i][j]=0; } void addVertex(String s) { int x=search(s); if(x==-1) { ver[nverts++]=s; size=nverts;} else System.out.println("sorry........................vertex already existed"); } void addEdge(String v,String w) { int i,j; i=index(v); j=index(w); if((i<size)&&(j<size)) { a[i][j]=1; a[j][i]=1; } else System.out.println("invalid edges"); } void displayAdj() { int i,j; displayVertex(); for(i=0;i<size;i++) { System.out.print(ver[i]+" "); for(j=0;j<size;j++) System.out.print(a[i][j]+" "); System.out.println(); } } Page 65 int index(String v) { for(int i=0;i< size;i++) { if(ver[i].equals(v)) return i; } return a.length; } void displayEdges() { int i,j; for(i=0;i<size;i++) { for(j=0;j<size;j++) if(a[i][j]==1) System.out.println(ver[i]+"->"+ver[j]); } } void displayVertex() { for(int i=0;i<size;i++) System.out.print(" "+ver[i]); System.out.println(); } int search(String s) { int i; for(i=0;i<size;i++) { if(ver[i].equals(s)) return i; } return -1; } String deleteVertex(int n) { String ss=ver[n]; if(n<size) { for(int i=n;i<=size;i++) { for(int j=n;j<=size;j++) a[i][j]=a[i][j+1]; ver[i]=ver[i+1]; } for(int j=n;j<=size;j++) { for(int i=n;i<=size;i++) a[i][j]=a[i+1][j];} Page 66 size --; nverts --; return ss; } else { size --; nverts --; return ss; } } void removeEdge(String v,String w) { int i,j; i=index(v); j=index(w); if((i<size)&&(j<size)) { a[i][j]=0; a[j][i]=0; } else System.out.println("invalid edges"); } void BFS(String v) { queue q=new queue(10); int mark[]=new int[size]; for(int i=0;i<size;i++) mark[i]=0; int k=index(v); mark[k]=1; q.insert(v); while(!q.isempty()) { String s=q.delete(); System.out.println(s); int i=index(s); for(int j=0;j<size;j++) { if(a[i][j]!=0&&mark[j]!=1) { mark[j]=1; q.insert(ver[j]); } } } } void DFS(String v) { stack s=new stack(size); Page 67 int mark1[]=new int[size]; for( int i=0;i<size;i++) mark1[i]=0; int i=index(v); System.out.println(ver[i]); s.push(v); mark1[i]=1; while(!s.isempty()) { for(int j=0;j<size;j++) { int id=index(s.peek()); if(a[id][j]!=0&&mark1[j]!=1) { s.push(ver[j]); mark1[j]=1; System.out.println(ver[j]); j= -1; } } s.pop() ; } } } // Graph.java import java.io.*; import java.util.*; class Graph { public static void main (String str[]) { Graph1 g=new Graph1(); Scanner sm=new Scanner(System.in); int ch; do { System.out.println(); System.out.println("1.AddVertex"); System.out.println("2.removeVertex"); System.out.println("3.AddEdge"); System.out.println("4.removeEdge"); System.out.println("5.DisplayAdjacentMatrix"); System.out.println("6.DisplayEdges"); System.out.println("7.BFS"); System.out.println("8.DFS"); System.out.println("0.exit()"); System.out.println("enter ur choice"); ch=sm.nextInt(); switch(ch) { Page 68 case 1:System.out.println("enter vertex"); String s1=sm.next(); g.addVertex(s1); break; case 2:System.out.println("enter vertex"); String find=sm.next(); int k=g.search(find); if(k!= -1) { System.out.println("at:"+k); System.out.println("deleted:"+g.deleteVertex(k)); } else System.out.println("vertex not found try again......................! "); break; case 3:System.out.println("enter 2 vertices for creating edge"); String s2=sm.next(); String s3 =sm.next(); g.addEdge(s2,s3); break; case 4:System.out.println("enter 2 vertices for deleteing edge"); String s4=sm.next(); String s5=sm.next(); g.removeEdge(s4,s5); break; case 5:g.displayAdj(); break; case 6:g.displayEdges(); break; case 7: System.out.println("enter vertex"); String s=sm.next(); g.BFS(s); break; case 8: System.out.println("enter vertex"); String sm1=sm.next(); g.DFS(sm1); break; } } while(ch!=0); } } /* I:\M.Tech Lab\14>java Graph 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix Page 69 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 1 enter vertex A 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 1 enter vertex B 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 1 enter vertex C 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 1 enter vertex D Page 70 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 1 enter vertex E 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 6 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 3 enter 2 vertices for creating edge E B 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice Page 71 3 enter 2 vertices for creating edge C D 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 3 enter 2 vertices for creating edge A E 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 3 enter 2 vertices for creating edge B C 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 5 ABCDE A00001 B00101 C01010 D00100 Page 72 E11000 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 4 enter 2 vertices for deleteing edge B E 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 5 ABCDE A00001 B00100 C01010 D00100 E10000 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice 6 A->E B->C C->B C->D D->C Page 73 E->A 1.AddVertex 2.removeVertex 3.AddEdge 4.removeEdge 5.DisplayAdjacentMatrix 6.DisplayEdges 7.BFS 8.DFS 0.exit() enter ur choice */ 15) Write Java programs for implementing the following sorting methods: a) Bubble sort d) Merge sort g) Binary tree sort b) Insertion sort e) Heap sort c) Quick sort f) Radix sort a) Bubble Sort // BubbleSort.java public class BubbleSort { // logic to sort the elements public static void bubble_srt(int array[]) { int n = array.length; int k; for (int m = n; m >= 0; m--) { for (int i = 0; i < n - 1; i++) { k = i + 1; if (array[i] > array[k]) { swapNumbers(i, k, array); } } printNumbers(array); } } private static void swapNumbers(int i, int j, int[] array) { int temp; temp = array[i]; array[i] = array[j]; array[j] = temp; } private static void printNumbers(int[] input) { for (int i = 0; i < input.length; i++) { System.out.print(input[i] + ", "); } System.out.println("\n"); } public static void main(String[] args) { int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 }; bubble_srt(input); Page 74 } } /* Output: G:\ Sorting>java BubbleSort 2, 4, 6, 9, 12, 23, 0, 1, 34, 2, 4, 6, 9, 12, 0, 1, 23, 34, 2, 4, 6, 9, 0, 1, 12, 23, 34, 2, 4, 6, 0, 1, 9, 12, 23, 34, 2, 4, 0, 1, 6, 9, 12, 23, 34, 2, 0, 1, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, 0, 1, 2, 4, 6, 9, 12, 23, 34, */ b) Insertion Sort // InsertionSort.java public class InsertionSort { public static void main(String a[]){ int[] arr1 = {10,34,2,56,7,67,88,42}; int[] arr2 = doInsertionSort(arr1); for(int i:arr2){ System.out.print(i); System.out.print(", "); } } public static int[] doInsertionSort(int[] input) { int temp; for (int i = 1; i < input.length; i++) { for(int j = i ; j > 0 ; j--){ if(input[j] < input[j-1]){ temp = input[j]; input[j] = input[j-1]; input[j-1] = temp; } } } return input; } } Page 75 /* Output: G:\ Sorting>java InsertionSort 2, 7, 10, 34, 42, 56, 67, 88, */ C) QuickSort // QuickSort.java public class QuickSort { private int array[]; private int length; public void sort(int[] inputArr) { if (inputArr == null || inputArr.length == 0) { return; } this.array = inputArr; length = inputArr.length; quickSort(0, length - 1); } private void quickSort(int lowerIndex, int higherIndex) { int i = lowerIndex; int j = higherIndex; // calculate pivot number, I am taking pivot as middle index number int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2]; // Divide into two arrays while (i <= j) { /** * In each iteration, we will identify a number from left side which * is greater then the pivot value, and also we will identify a number * from right side which is less then the pivot value. Once the search * is done, then we exchange both numbers. */ while (array[i] < pivot) { i++; } while (array[j] > pivot) { j--; } if (i <= j) { exchangeNumbers(i, j); //move index to next position on both sides i++; j--; } } // call quickSort() method recursively if (lowerIndex < j) quickSort(lowerIndex, j); if (i < higherIndex) quickSort(i, higherIndex); } Page 76 private void exchangeNumbers(int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } public static void main(String a[]){ QuickSort sorter = new QuickSort(); int[] input = {24,2,45,20,56,75,2,56,99,53,12}; sorter.sort(input); for(int i:input){ System.out.print(i); System.out.print(" "); } } } /* Output: G:\ Sorting>java QuickSort 2 2 12 20 24 45 53 56 56 75 99 */ D)Merge Sort // MergeSort.java public class MergeSort { private int[] array; private int[] tempMergArr; private int length; public static void main(String a[]){ int[] inputArr = {45,23,11,89,77,98,4,28,65,43}; MergeSort mms = new MergeSort(); mms.sort(inputArr); for(int i:inputArr){ System.out.print(i); System.out.print(" "); } } public void sort(int inputArr[]) { this.array = inputArr; this.length = inputArr.length; this.tempMergArr = new int[length]; doMergeSort(0, length - 1); } private void doMergeSort(int lowerIndex, int higherIndex) { if (lowerIndex < higherIndex) { int middle = lowerIndex + (higherIndex - lowerIndex) / 2; // Below step sorts the left side of the array doMergeSort(lowerIndex, middle); // Below step sorts the right side of the array doMergeSort(middle + 1, higherIndex); // Now merge both sides Page 77 } mergeParts(lowerIndex, middle, higherIndex); } private void mergeParts(int lowerIndex, int middle, int higherIndex) { for (int i = lowerIndex; i <= higherIndex; i++) { tempMergArr[i] = array[i]; } int i = lowerIndex; int j = middle + 1; int k = lowerIndex; while (i <= middle && j <= higherIndex) { if (tempMergArr[i] <= tempMergArr[j]) { array[k] = tempMergArr[i]; i++; } else { array[k] = tempMergArr[j]; j++; } k++; } while (i <= middle) { array[k] = tempMergArr[i]; k++; i++; } } } /* Output: G:\ Sorting>java MergeSort 4 11 23 28 43 45 65 77 89 98 */ E)Heap Sort // Heap Sort.java import java.io.BufferedReader; import java.io.InputStreamReader; public class HeapSort { private static int[] a; private static int n; private static int left; private static int right; private static int largest; public static void buildheap(int []a){ n=a.length-1; for(int i=n/2;i>=0;i--){ maxheap(a,i); } } public static void maxheap(int[] a, int i){ left=2*i; Page 78 right=2*i+1; if(left <= n && a[left] > a[i]){ largest=left; } else{ largest=i; } if(right <= n && a[right] > a[largest]){ largest=right; } if(largest!=i){ exchange(i,largest); maxheap(a, largest); } } public static void exchange(int i, int j){ int t=a[i]; a[i]=a[j]; a[j]=t; } public static void sort(int []a0){ a=a0; buildheap(a); for(int i=n;i>0;i--){ exchange(0, i); n=n-1; maxheap(a, 0); } } public static void main(String[] args) throws Exception { InputStreamReader isr; isr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); System.out.print("How many values to sort? "); int n=Integer.parseInt(in.readLine()); int a1[]=new int[n]; for(int i=0;i<n;i++) { System.out.print("Enter value "+ (i+1) +" : "); a1[i]=Integer.parseInt(in.readLine()); } //int []a1={4,1,3,2,16,9,10,14,8,7}; sort(a1); for(int i=0;i<a1.length;i++){ System.out.print(a1[i] + " "); } } } /* Output: G:\ >java HeapSort How many values to sort? 5 Page 79 Enter value 1 : 15 Enter value 2 : 18 Enter value 3 : 25 Enter value 4 : 69 Enter value 5 : 11 11 15 18 25 69 */ F) RadixSort.java //RadixSort.java import java.io.BufferedReader; import java.io.InputStreamReader; class RadixSort { static void radixsort(int a[],int d) { int bmat[][],c[],e=1; int i, j, k, m, digit, row, col; bmat=new int[a.length][10]; c= new int[10]; for(m=1;m<=d;m++) { for(i=0;i<10;i++) { c[i]=-1; } for(i=0;i<a.length;i++) { digit=(a[i]/e)%10; c[digit]++; row=c[digit]; col=digit; bmat[row][col]=a[i]; } k=-1; for(i=0;i<10;i++) { if(c[i]!=-1) { for(j=0;j<=c[i];j++) { k++; a[k]=bmat[j][i]; } } } e=e*10; } } public static void main (String args[]) throws Exception { Page 80 } InputStreamReader isr; isr = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(isr); System.out.print("How many values to sort? "); int n=Integer.parseInt(in.readLine()); int a[]=new int[n]; for(int i=0;i<n;i++) { System.out.print("Enter value "+ (i+1) +" : "); a[i]=Integer.parseInt(in.readLine()); } radixsort(a,3); System.out.println("\n" + "Sorted array:"); for(int i=0;i<n;i++) { System.out.print(a[i] + " "); } System.out.println(); } /* Output: G:\ Sorting>java RadixSort How many values to sort? 4 Enter value 1 : 12 Enter value 2 : 13 Enter value 3 : 15 Enter value 4 : 26 Sorted array: 12 13 15 26 */ G)BinaryTree // BinaryTree.java public class BinaryTree { public static void main(String[] args) { new BinaryTree().run(); } static class Node { Node left; Node right; int value; } public Node(int value) { this.value = value; } Page 81 public void run() { // build the simple tree from chapter 11. Node root = new Node(5); System.out.println("Binary Tree"); System.out.println("============="); System.out.println("Building tree with root value " + root.value); insert(root, 1); insert(root, 8); insert(root, 6); insert(root, 3); insert(root, 9); System.out.println("Traversing tree in order"); printInOrder(root); System.out.println("Traversing tree front-to-back from location 7"); printFrontToBack(root, 7); } 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.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.value); node.right = new Node(value); } } } public void printInOrder(Node node) { if (node != null) { printInOrder(node.left); System.out.println(" Traversed " + node.value); printInOrder(node.right); } } /* * uses in-order traversal when the origin is less than the node's value * uses reverse-order traversal when the origin is greater than the node's order */ public void printFrontToBack(Node node, int camera) { if (node == null) return; if (node.value > camera) { // print in order Page 82 printFrontToBack(node.left, camera); System.out.println(" Traversed " + node.value); printFrontToBack(node.right, camera); } else if (node.value < camera) { // print reverse order printFrontToBack(node.right, camera); System.out.println(" Traversed " + node.value); printFrontToBack(node.left, camera); } else { // order doesn't matter printFrontToBack(node.left, camera); printFrontToBack(node.right, camera); } } } /* Output: I:\M.Tech Lab\15>java BinaryTree Binary Tree ============= Building tree with root value 5 Inserted 1 to left of 5 Inserted 8 to right of 5 Inserted 6 to left of 8 Inserted 3 to right of 1 Inserted 9 to right of 8 Traversing tree in order Traversed 1 Traversed 3 Traversed 5 Traversed 6 Traversed 8 Traversed 9 Traversing tree front-to-back from location 7 Traversed 6 Traversed 8 Traversed 9 Traversed 5 Traversed 3 Traversed 1 */ 16) Write a Java program to perform the following operations: a) Insertion into a B-tree b) Searching in a B-tree // Tree.java class Tree { Tree left ; Tree right; int key ; boolean has_left ; boolean has_right ; Page 83 Tree my_null ; // Initialize a node with a key value and no children public boolean Init(int v_key){ key = v_key ; has_left = false ; has_right = false ; return true ; } // Update the right child with rn public boolean SetRight(Tree rn){ right = rn ; return true ; } // Update the left child with ln public boolean SetLeft(Tree ln){ left = ln ; return true ; } public Tree GetRight(){ return right ; } public Tree GetLeft(){ return left; } public int GetKey(){ return key ; } public boolean SetKey(int v_key){ key = v_key ; return true ; } public boolean GetHas_Right(){ return has_right ; } public boolean GetHas_Left(){ return has_left ; } public boolean SetHas_Left(boolean val){ has_left = val ; return true ; } public boolean SetHas_Right(boolean val){ has_right = val ; return true ; } // This method compares two integers and returns true if they are equal and false public boolean Compare(int num1 , int num2){ boolean bool ; int nti ; bool = false ; Page 84 nti = num2 + 1 ; if (num1 < num2) bool = false ; else if (!(num1 < nti)) bool = false ; else bool = true ; return bool ; } // Insert a new element in the tree public boolean Insert(int v_key){ Tree new_node ; boolean bool ; boolean cont ; int keyValue ; Tree cNode ; new_node = new Tree(); bool = new_node.Init(v_key) ; cNode = this ; cont = true ; while (cont){ keyValue = cNode.GetKey(); if (v_key < keyValue){ if (cNode.GetHas_Left()) cNode = cNode.GetLeft() ; else { cont = false ; bool = cNode.SetHas_Left(true); bool = cNode.SetLeft(new_node); } } else{ if (cNode.GetHas_Right()) cNode = cNode.GetRight() ; else { cont = false ; bool = cNode.SetHas_Right(true); bool = cNode.SetRight(new_node); } } } return true ; } // Delete an element from the tree public boolean Delete(int v_key){ Tree cNode ; Tree parent_node ; boolean cont ; boolean found ; boolean is_root ; int keyValue ; Page 85 boolean bool ; cNode = this ; parent_node = this ; cont = true ; found = false ; is_root = true ; while (cont){ keyValue = cNode.GetKey(); if (v_key < keyValue) if (cNode.GetHas_Left()){ parent_node = cNode ; cNode = cNode.GetLeft() ; } else cont = false ; else if (keyValue < v_key) if (cNode.GetHas_Right()){ parent_node = cNode ; cNode = cNode.GetRight() ; } else cont = false ; else { if (is_root) if ((!cNode.GetHas_Right()) && (!cNode.GetHas_Left()) ) bool = true ; else bool = this.Remove(parent_node,cNode); else bool = this.Remove(parent_node,cNode); found = true ; cont = false ; } is_root = false ; } return found ; } // Check if the element to be removed will use the, righ or left subtree if one exists public boolean Remove(Tree p_node, Tree c_node){ boolean bool ; int auxkey1 ; int auxkey2 ; if (c_node.GetHas_Left()) bool = this.RemoveLeft(p_node,c_node) ; else if (c_node.GetHas_Right()) bool = this.RemoveRight(p_node,c_node) ; else { auxkey1 = c_node.GetKey(); auxkey2 = (p_node.GetLeft()).GetKey() ; if (this.Compare(auxkey1,auxkey2)) { Page 86 bool = p_node.SetLeft(my_null); bool = p_node.SetHas_Left(false); } else { bool = p_node.SetRight(my_null); bool = p_node.SetHas_Right(false); } } return true ; } public boolean RemoveRight(Tree p_node, Tree c_node){ boolean bool ; while (c_node.GetHas_Right()){ bool = c_node.SetKey((c_node.GetRight()).GetKey()); p_node = c_node; c_node = c_node.GetRight() ; } bool = p_node.SetRight(my_null); bool = p_node.SetHas_Right(false); return true ; } public boolean RemoveLeft(Tree p_node, Tree c_node){ boolean bool; while (c_node.GetHas_Left()){ bool = c_node.SetKey((c_node.GetLeft()).GetKey()); p_node = c_node ; c_node = c_node.GetLeft() ; } bool = p_node.SetLeft(my_null); bool = p_node.SetHas_Left(false); return true ; } // Search for an elemnt in the tree public int Search(int v_key){ boolean cont ; int ifound ; Tree cNode; int keyValue ; cNode = this ; cont = true ; ifound = 0 ; while(cont){ keyValue = cNode.GetKey(); if (v_key < keyValue) if (cNode.GetHas_Left()) cNode = cNode.GetLeft() ; else cont = false ; else Page 87 if (keyValue < v_key) if (cNode.GetHas_Right()) cNode = cNode.GetRight() ; else cont = false ; else { ifound = 1 ; cont = false ; } } return ifound ; } // Invoke the method to really print the tree elements public boolean Print(){ Tree cNode; boolean bool ; cNode = this ; bool = this.RecPrint(cNode); return true ; } // Print the elements of the tree public boolean RecPrint(Tree node){ boolean bool ; if (node.GetHas_Left()){ bool = this.RecPrint(node.GetLeft()); } else bool = true ; System.out.println(node.GetKey()); if (node.GetHas_Right()){ bool = this.RecPrint(node.GetRight()); } else bool = true ; return true ; } } // Binarytree.java class Binarytree { public int Start() { Tree root; boolean bool; int nti; root = new Tree(); bool = root.Init(16); bool = root.Print(); System.out.println(100); bool = root.Print(); System.out.println("After Inserting data is! "); bool = root.Insert(8); bool = root.Insert(24); Page 88 bool = root.Insert(40); bool = root.Insert(12); bool = root.Insert(20); bool = root.Insert(28); bool = root.Insert(14); bool = root.Insert(25); bool = root.Insert(25); bool = root.Print(); System.out.println("Search value is: " + root.Search(24)); System.out.println("Search value is: " + root.Search(12)); System.out.println("Search value is: " + root.Search(16)); System.out.println("Search value is: " + root.Search(50)); System.out.println("Search value is: " + root.Search(12)); System.out.println("Search value is: " + root.Search(25)); System.out.println("After deleting data! "); bool = root.Delete(12); bool = root.Delete(25); bool = root.Print(); System.out.println(root.Search(12)); System.out.println("Delete value is: " + root.Delete(12)); System.out.println("Delete value is: " + root.Delete(25)); return 0 ; } public static void main(String args[]) { System.out.println(new Binarytree().Start()); } } /* Output: I:\M.Tech Lab\16>java Binarytree 16 100 16 After Inserting data is! 8 12 14 16 20 24 25 25 28 40 Search value is: 1 Search value is: 1 Search value is: 1 Search value is: 0 Search value is: 1 Page 89 Search value is: 1 After deleting data! 8 14 16 20 24 25 28 40 0 Delete value is: false Delete value is: true 0 */ 17) Write a Java program that implements Kruskal’s algorithm to generate minimum cost spanning tree. //Edge.java class Edge implements Comparable<Edge> { String vertexA, vertexB; int weight; public Edge(String vertexA, String vertexB, int weight) { this.vertexA = vertexA; this.vertexB = vertexB; this.weight = weight; } public String getVertexA() { return vertexA; } public String getVertexB() { return vertexB; } public int getWeight() { return weight; } @Override public String toString() { return "(" + vertexA + ", " + vertexB + ") : Weight = " + weight; } public int compareTo(Edge edge) { //== is not compared so that duplicate values are not eliminated. return (this.weight < edge.weight) ? -1: 1; } } Page 90 // KruskalEdges.java import java.util.TreeSet; import java.util.Vector; import java.util.HashSet; class KruskalEdges { Vector<HashSet<String>> vertexGroups = new Vector<HashSet<String>>(); TreeSet<Edge> kruskalEdges = new TreeSet<Edge>(); public TreeSet<Edge> getEdges() { return kruskalEdges; } HashSet<String> getVertexGroup(String vertex) { for (HashSet<String> vertexGroup : vertexGroups) { if (vertexGroup.contains(vertex)) { return vertexGroup; } } return null; } public void insertEdge(Edge edge) { String vertexA = edge.getVertexA(); String vertexB = edge.getVertexB(); HashSet<String> vertexGroupA = getVertexGroup(vertexA); HashSet<String> vertexGroupB = getVertexGroup(vertexB); if (vertexGroupA == null) { kruskalEdges.add(edge); if (vertexGroupB == null) { HashSet<String> htNewVertexGroup = new HashSet<String>(); htNewVertexGroup.add(vertexA); htNewVertexGroup.add(vertexB); vertexGroups.add(htNewVertexGroup); } else { vertexGroupB.add(vertexA); } } else { if (vertexGroupB == null) { vertexGroupA.add(vertexB); kruskalEdges.add(edge); } else if (vertexGroupA != vertexGroupB) { vertexGroupA.addAll(vertexGroupB); vertexGroups.remove(vertexGroupB); kruskalEdges.add(edge); Page 91 } } } } // Kruskal.java import java.util.TreeSet; public class Kruskal { public static void main(String[] args) { //TreeSet is used to sort the edges before passing to the algorithm TreeSet<Edge> edges = new TreeSet<Edge>(); //Sample problem - replace these values with your problem set edges.add(new Edge("0", "1", 2)); edges.add(new Edge("0", "3", 1)); edges.add(new Edge("1", "2", 3)); edges.add(new Edge("2", "3", 5)); edges.add(new Edge("2", "4", 7)); edges.add(new Edge("3", "4", 6)); edges.add(new Edge("4", "5", 4)); System.out.println("Graph"); KruskalEdges vv = new KruskalEdges(); for (Edge edge : edges) { System.out.println(edge); vv.insertEdge(edge); } System.out.println("MINIMUM SPANNING TREE"); int total = 0; for (Edge edge : vv.getEdges()) { System.out.println(edge); total += edge.getWeight(); } System.out.println("Total weight is " + total); } } /* Output: I:\M.Tech Lab\17>java Kruskal Graph (0, 3) : Weight = 1 (0, 1) : Weight = 2 (1, 2) : Weight = 3 (4, 5) : Weight = 4 (2, 3) : Weight = 5 (3, 4) : Weight = 6 (2, 4) : Weight = 7 MINIMUM SPANNING TREE (0, 3) : Weight = 1 (0, 1) : Weight = 2 Page 92 (1, 2) : Weight = 3 (4, 5) : Weight = 4 (3, 4) : Weight = 6 Total weight is 16 */ 18) Write a Java program that implements KMP algorithm for pattern matching. //KMP.java class KMP { public static void main(String[] args) { String T = "INCREDIBLE INDIAN"; String P = "EC"; boolean isMatch = kmp(T, P); if(isMatch) System.out.println("Pattern " + P + " is present in text: " + T); else System.out.println("Pattern " + P + " is not present in text: " + T); } static boolean kmp(String T, String P) { int n = T.length(); int m = P.length(); int[] fail = computeFailFunction(P); int i = 0; // text index int j = 0; // pattern index while( i < n ) { if( P.charAt(j) == T.charAt(i) ) { if( j == m-1 ) return true; i++; j++; } else if( j > 0 ) j = fail[j-1]; else i++; } return false; } static int[] computeFailFunction( String P ) { int m = P.length(); int[] fail = new int[m]; fail[0] = 0; int i = 1; int j = 0; while( i < m ) { Page 93 if( P.charAt(j) == P.charAt(i) ) // j+1 characters match { fail[i] = j+1; i++; j++; } else if( j > 0 ) // j follows a matching prefix j = fail[j-1]; else // no match { fail[i] = 0; i++; } } return fail; } } /* Output: I:\M.Tech Lab\18>java KMP Pattern CRED is present in text: INCREDIBLE INDIAN. I:\M.Tech Lab\18>javac KMP.java I:\M.Tech Lab\18>java KMP Pattern EC is not present in text: INCREDIBLE INDIAN. */