Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
DATA STRUCTURES AND ALGORITHMS LABPROGRAMS ON DATA STRUCTURES:
(1) Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative, display a message stating that there are no real solutions.
import java.io.*;class QuadraticEquationPgm1{public static void main(String args[]) throws IOException{double a, b, c, sq, r1, r2;BufferedReader br = new BufferedReader(new InputStreamReader(System.in));System.out.println("enter the value of a");a = Float.parseFloat(br.readLine());System.out.println("enter the value of b");b = Float.parseFloat(br.readLine());System.out.println("enter the value of c");c = Float.parseFloat(br.readLine());sq = Math.sqrt(b * b - 4 * a * c);if (sq == 0){r1 = -b / (2 * a);r2 = r1;System.out.println("The roots are real and equal");System.out.println("The roots are:" + r1 + "," + r2);}else if (sq > 0){r1 = (-b + sq) / (2 * a);r2 = (-b - sq) / (2 * a);System.out.println("The roots are real but not equal");System.out.println("The roots are:" + r1 + "," + r2);}else{System.out.println("There are no real solutions");}}
} (2) The Fibonacci sequence is defined by the following rule. The first two values in the sequence are 1 and 1. Every subsequent value is the run of the two values preceding it. Write a Java program that uses both recursive and non recursive functions to print the nth value in the Fibonacci sequence. import java.io.*;class Fibonacci{
1
int a1,a2,a3,num,i; int fibRec(int x) { if(x==0) return 0; else if(x==1) return 1; else return (fibRec(x-1)+fibRec(x-2)); } int fibNonRec(int y) { a1=1; a2=1;num=y; for(i=3;i<=num;i++) { a3=a1+a2; a1=a2; a2=a3; } return a3; }}class FibonacciPgm2{ public static void main(String args[]) throws IOException { int n; System.out.println("enter n value"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); n=Integer.parseInt(br.readLine()); Fibonacci f=new Fibonacci(); System.out.println("The nth value with recursive:"+f.fibRec(n)); System.out.println("The nth value with non-recursive:"+f.fibNonRec(n)); }}
(3) Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that integer.
import java.io.*;class PrimeNumberPgm3{ public static void main(String args[]) throws IOException { int n; System.out.println("Enter a number"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); n=Integer.parseInt(br.readLine());
2
System.out.println("The prime numbers below "+n+" are:"); for(int i=1;i<=n;i++) { int count=0; for(int j=1;j<=i;j++) { if(i%j==0) count++; } if(count==2) System.out.print(i+" "); } }}
(4) Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome. import java.io.*;class PalindromePgm4{ public static void main(String args[]) throws IOException { String str; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter a name"); str=br.readLine(); int len=str.length(); String revstr=""; for(int i=len-1;i>=0;i--) revstr=revstr+str.charAt(i); if(str.equals(revstr)) System.out.println(str+" is a palindrome"); else System.out.println(str+" is not a palindrome"); }}
(5) Write a Java program for sorting a given list of names in ascending order.
import java.io.*;class NamesSortingPgm5{ public static void main(String args[]) throws IOException { int n,i,j; System.out.println("Enter no.of names"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); n=Integer.parseInt(br.readLine()); String arr[]=new String[n]; System.out.println("Enter list of names");
3
for(i=0;i<n;i++) arr[i]=br.readLine(); System.out.println("The list of names after sorting are:"); for(i=0;i<arr.length;i++) { for(j=i+1;j<arr.length;j++) { if(arr[j].compareTo(arr[i])<0) {String t=arr[i]; arr[i]=arr[j]; arr[j]=t; } } } for(i=0;i<arr.length;i++) System.out.println(arr[i]); }}
6) Write a Java program to multiply two given matrices.import java.io.*;class MatrixMultiplicationPgm6{ public static void main(String args[])throws IOException { int r1,r2,c1,c2,a[][],b[][],c[][],i,j,k; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter number of rows for the first matrix"); r1=Integer.parseInt(br.readLine()); System.out.println("Enter number of columns for the first matrix"); c1=Integer.parseInt(br.readLine()); System.out.println("Enter number of rows for the second matrix"); r2=Integer.parseInt(br.readLine()); System.out.println("Enter number of columns for the second matrix"); c2=Integer.parseInt(br.readLine()); a=new int[r1][c1]; b=new int[r2][c2]; System.out.println("Enter elements for the first matrix"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) a[i][j]=Integer.parseInt(br.readLine()); } System.out.println("Enter elements for the second matrix"); for(i=0;i<r2;i++) { for(j=0;j<c2;j++) b[i][j]=Integer.parseInt(br.readLine()); }
4
c=new int[r1][c2]; if(c1==r2) { for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { c[i][j]=0; for(k=0;k<r2;k++) { c[i][j]=c[i][j]+(a[i][k]*b[k][j]); } } } System.out.println("The result is:"); for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { System.out.print(c[i][j]+"\t"); } System.out.println("\n"); } } else { System.out.println("Matrix multiplication is not possible");} }}
(7) Write a Java Program that reads a line of integers, and then displays each integers, and the sum of all the integers (use string tokenizer class)
import java.util.*;import java.io.*;class TokenizerSumPgm7{ public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter a line of integers"); String str=br.readLine(); StringTokenizer st=new StringTokenizer(str); int sum=0; System.out.println("The entered integers are:"); while(st.hasMoreTokens()) { String s1=st.nextToken(); int n=Integer.parseInt(s1); System.out.println(n);
5
sum=sum+n; } System.out.println("The sum of entered integers:"+sum); }}
(8) Write a Java program that reads on file name from the user then displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes.
import java.io.*;import javax.swing.*;class FileInfoPgm8{ public static void main(String args[]) throws IOException { String fname; System.out.println("enter a file name"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); fname=br.readLine(); JFileChooser ch=new JFileChooser(); File f1=new File(fname); if(f1.exists()) { System.out.println("The file "+fname+" exists"); if(f1.canRead()) System.out.println("The file "+fname+" is readable"); if(f1.canWrite()) System.out.println("The file "+fname+" is writable"); System.out.println("The length of the file in bytes:"+f1.length()); System.out.println("The type of file is:"+ch.getTypeDescription(f1)); } else System.out.println("The file "+fname+" does not exist"); }}
(9) Write a Java program that reads a file and displays a file and displays the file on the screen, with a line number before each line.
import java.io.*;class FileLineNumberPgm9{ public static void main(String args[])throws IOException { char ch; int lNo,size; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter a file name"); FileInputStream fis=new FileInputStream(br.readLine());
6
size=fis.available(); lNo=0; System.out.print(++lNo+":"); ch=(char)fis.read(); System.out.print(ch); for(int i=1;i<size;i++) { if(ch=='\n') { lNo=lNo+1; System.out.print(lNo+":"); } ch=(char)fis.read(); System.out.print(ch); } }}
(10) Write a Java program that displays the number of characters, lines and words in a text file.
import java.io.*;import java.io.FileInputStream;class FileCharWordLineCount10{public static void main(String args[]) throws IOException{BufferedReader br = new BufferedReader(new InputStreamReader(System.in));String str;int i,count = 0,word = 0,line = 0;System.out.println("Enter the file name:");str = br.readLine();FileInputStream fis = new FileInputStream(str);
do{
i = fis.read(); if(i != -1) { System.out.print((char)i); count++; if((char)i == '\n' || (char)i == ' ') word++; if((char)i == '\n') line++; } } while(i != -1);System.out.println();System.out.println("Number of characters :"+" "+(count-word-line));System.out.println("Number of words :"+" "+(word));System.out.println("Number of line :"+" "+line);
7
}}(11) Write a Java program for creating multiple threadsa) Using Thread class
class NewThread extends Thread{ NewThread() { super("Demo Thread"); System.out.println("Child Thread:"+this); start(); } public void run() { try { for(int i=0;i<=3;i++) { System.out.println("Child Thread:"+i); Thread.sleep(500); } }` catch(InterruptedException e) { System.out.println("child interrupted"); } System.out.println("exiting child thread"); }}class ExtendedThreadPgm11a{ public static void main(String args[]) { new NewThread(); try { for(int i=0;i<5;i++) { System.out.println("Main Thread:"+i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("Main Thread Interrupted"); } System.out.println("Main thread exiting");}}
8
(11b) Using Runnable interface
class RunThread implements Runnable{ String name; Thread t; RunThread(String tname) { name=tname; t=new Thread(this,name); System.out.println(name+":"+t); t.start(); } public void run() { try { System.out.println("entering child thread"); for(int i=0;i<=2;i++) System.out.println(name+":"+i); Thread.sleep(1000); } catch(InterruptedException ie) { System.out.println(ie); } System.out.println(name+" exiting"); }}class RunnableThreadPgm11b{ public static void main(String args[]) { new RunThread("one"); new RunThread("two"); try { System.out.println("entering main thread"); for(int i=0;i<=3;i++) { System.out.println("main thread:"+i); Thread.sleep(2000); } } catch(InterruptedException ie) { System.out.println(ie); } System.out.println("exiting main thread"); }}
9
(12) Write a Java program that illustrates how run time polymorphism is achieved.
class Figure{ double d1, d2; Figure(double a, double b) { d1 = a; d2 = b; } double area() { System.out.println("Area of the figure"); return 0; }}class Rectangle extends Figure{ Rectangle(double a, double b) { super(a, b); } double area() { System.out.println("Area of rectangle"); return d1 * d2; }}class Triangle extends Figure{ Triangle(double a, double b) { super(a, b); } double area() { System.out.println("Area of triangle"); return (d1 * d2 / 2); }}class RunTimePolymorphismPgm12{ public static void main(String[] args) { Figure f = new Figure(2,5); Rectangle r = new Rectangle(10,20); Triangle t = new Triangle(6,30); System.out.println(f.area()); f = r; System.out.println(f.area());
10
f = t; System.out.println(f.area()); }}
(13)(a) Write a java program that illustrates the followinga) Creation of simple package.
/*(1) save this file in MyPack folder as SimplePackage13a.java(2)compile: javac SimplePackage13a.java(3)To run:go to parent directory java MyPack.SimplePackage13a*/package MyPack;class GetDis{ String name; int Hno; void getdata(String str,int no) { name=str; Hno=no; } void display() { System.out.println("Name:"+name+"\n"+"Hall Ticket No:"+Hno); }}class SimplePackage13a{ public static void main(String args[]) { GetDis g=new GetDis(); g.getdata("sowmya",543); g.display(); g.getdata("swathi",224); g.display(); }}
(13b)(i)Accessing a Package
package pack2;public class Addition{ int a,b,s; public void getdata(int x,int y) { a=x;
11
b=y; } public void sum() { s=a+b; } public void display() { System.out.println("sum="+s); }}
(ii)import pack2.*;class ImportPackage{ public static void main(String args[]) { Addition a1=new Addition(); a1.getdata(5,7); a1.sum(); a1.display(); }} (13)(c) Implementing Interfaces
interface if1{ final int a=10; void display();}interface if2{ final int b=45; void sum();}class InterfaceDemo implements if1,if2{ int s; public void sum() { s=a+b; } public void display() { System.out.println("Sum="+s); }}class InterfacePgm13c{
12
public static void main(String args[]) { InterfaceDemo id=new InterfaceDemo(); id.sum(); id.display(); }}
(14)Write a java program that illustrates the following(a)Handling Predefined Exceptions
import java.io.*;class PredefinedExceptionPgm14a{ public static void main(String args[]) throws IOException { int d,a; try { System.out.println("enter a number"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); d=Integer.parseInt(br.readLine()); a=15/d; System.out.println("a="+a); } catch(ArithmeticException e) { System.out.println(e); } }}
(b)Handling User Defined Exceptions
import java.io.*;class MyException extends Exception{ int x; MyException(int n) { x=n; } public String toString() { return "MyException["+x+"]"; }}class UserDefinedException14b{ public static void main(String args[]) throws IOException,MyException
13
{ int a; System.out.println("enter a number"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); a=Integer.parseInt(br.readLine()); if(a>20) throw new MyException(a); else System.out.println("a="+a); }}
(15) Write Java programs that use both recursive and non-recursive functions forimplementing the following searching methodsa) Linear search
import java.io.*;
class LinearSearch{int a[],val;LinearSearch(int ele[],int keyValue){a=ele;val=keyValue;}public void recursiveLinearSearch(int n){if (n < 0)System.out.println("element not found(using recursive)");else{if (val == a[n])System.out.println("element found at location(using recursive)" + n);elserecursiveLinearSearch(n - 1);}}public void nonRecursiveLinearSearch(){int i, count = 0;for (i = 0; i < a.length; i++){if (a[i] == val){count++;break;}}if (count > 0)
14
System.out.println("element found at location(using non recursive):" + i);elseSystem.out.println("element not found(using non recursive)");
}}class LinearSearchPgm15a{public static void main(String args[])throws IOException{int n, i,key;int item[];BufferedReader br = new BufferedReader(new InputStreamReader(System.in));System.out.println("enter no.of elements");n = Integer.parseInt(br.readLine());item = new int[n];System.out.println("enter elements");for (i = 0; i < n; i++)item[i] = Integer.parseInt(br.readLine()); System.out.println("enter an element to be searched");key = Integer.parseInt(br.readLine());LinearSearch ls = new LinearSearch(item,key);ls.recursiveLinearSearch(item.length - 1);ls.nonRecursiveLinearSearch();
}}
(15)(b) Binary search
import java.io.*;class BinarySearch{int a[];int val;BinarySearch(int ele[],int keyValue){a = ele;val = keyValue;}boolean binarySearchRecursive(int low,int high){if( low > high ) return false;int mid = (low + high)/2;if( val < a[mid]) return binarySearchRecursive(low, mid-1);else if( val > a[mid])return binarySearchRecursive(mid+1, high);else return true;}
15
boolean binarySearchNonRecursive(){int c, mid, low = 0, high = a.length-1;while( low <= high){mid = (low + high)/2;if(val < a[mid])high = mid-1;else if( val> a[mid]) low = mid+1;else return true;}return false;}
}
class BinarySearchPgm15b{public static void main(String args[])throws IOException{int n, i,key,j;int item[];BufferedReader br = new BufferedReader(new InputStreamReader(System.in));System.out.println("enter no.of elements");n = Integer.parseInt(br.readLine());item = new int[n];System.out.println("enter elements");for (i = 0; i < n; i++)item[i] = Integer.parseInt(br.readLine()); for (i = 0; i < n; i++){for (j = i + 1; j < n; j++){if (item[i] > item[j]){int temp;temp = item[i];item[i] = item[j];item[j] = temp;}}}System.out.println("enter key element to be searched");key = Integer.parseInt(br.readLine());BinarySearch bs = new BinarySearch(item,key);if(bs.binarySearchRecursive(0,item.length-1))System.out.println(key + " found(using recursive)");elseSystem.out.println(key + " not found(using recursive)");
16
if (bs.binarySearchNonRecursive())System.out.println(key + " found(using non recursive)");elseSystem.out.println(key + " not found(using non recursive)");
}}
(16)(a) Write java programs to implement the following using arrays and linked listsa) List ADT
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();
}class ArrayList implements List{class Node{ Object data;int next;Node(Object ob, int i) // constructor{ data = ob;next = i;}}int MAXSIZE;Node list[];int head, count; ArrayList( int s){ 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
17
{ int p;for( p = 0; p < n; p++ ){list[p] = new Node(11+11*p, p+1);count++;}list[p-1].next = -1; }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");return;}int q = getNode(); int p = find(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;
18
}public int find(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.elsehead = list[head].next;count--; // update countreturn tmp;}public Object deleteAfter(Object x){ 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 + " ");p = list[p].next; // advance to next node}System.out.println("]\n");//
19
}public boolean isEmpty(){ if(count == 0)return true;else return false;}public int size(){ return count; }
}class ListADTArray16a{public static void main(String[] args){ArrayList linkedList = new ArrayList(10);linkedList.initializeList();linkedList.createList(4);linkedList.display(); System.out.print("InsertFirst 55:");linkedList.insertFirst(55);linkedList.display();System.out.print("Insert 66 after 33:");linkedList.insertAfter(66, 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);System.out.println("Deleted node: " + item);linkedList.display();System.out.println("size(): " + linkedList.size());}}
(16)(b)List ADT LinkedList
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();
}
20
class LinkedList implements List{class Node{ Object data;Node next;Node( Object d ){ data = d; }}Node head;Node p; int count;public void createList(int n) {p = new Node(11);head = p;for( int i = 1; i < n; i++ ) p = p.next = new Node(11 + 11*i);count = n;}public void insertFirst(Object item){p = new Node(item);p.next = head;head = p;count++;}public void insertAfter(Object item,Object key){p = find(key);if( p == null )System.out.println(key + " key is not found");else{ Node q = new Node(item);q.next = p.next; p.next = q; count++;}}public Node find(Object key){p = head;while( p != null ) {if( p.data == key )
return p;
21
p = p.next; }return null; }public Object deleteFirst(){if (isEmpty()){System.out.println("List is empty: no deletion");return null;}Node tmp = head;head = tmp.next;count--;return tmp.data;}public Object deleteAfter(Object key){p = find(key);if (p == null){System.out.println(key + " key is not found");return null;}if (p.next == null){System.out.println("No deletion");return null;}else{Node tmp = p.next;p.next = tmp.next;count--;return tmp.data;}}public void displayList(){p = head;System.out.print("\nLinked List: ");while (p != null){System.out.print(p.data + " -> ");p = p.next;}System.out.println(p);}public boolean isEmpty(){ return (head == null);}
22
public int size(){return count; }
} class ListADTLinkedList16b{ public static void main(String[] args){ LinkedList list = new LinkedList();list.createList(4);list.displayList();list.insertFirst(55);list.displayList();list.insertAfter(66, 33);list.displayList();Object item = list.deleteFirst();if( item != null ){ System.out.println("deleteFirst(): " + item);list.displayList();}item = list.deleteAfter(22);if( item != null ){ System.out.println("deleteAfter(22): " + item);list.displayList();}System.out.println("size(): " + list.size());}
}
(17) Write Java programs to implement the following using an array.a) Stack ADT
import java.io.*;interface StackADT{ public void push(Object o); public void pop(); public void display(); public boolean isEmpty(); public int size(); public Object peek();}
class ArrayStackADT implements StackADT{ Object a[];
23
int top; ArrayStackADT(int n) { a=new Object[n]; top=-1; } public void push(Object item) { if(top==a.length-1) { System.out.println("The stack is full"); } else { top++; a[top]=item; } } public boolean isEmpty() { if(top==-1) return true; else return false; } public void pop() { Object item; if(isEmpty()) { System.out.println("The stack is empty"); } else { item=a[top]; top--; System.out.println("The deleted item is:"+item); } } public void display() { if(isEmpty()) { System.out.println("The stack is empty"); } else { System.out.println("The contents of stack are:");
24
for(int i=0;i<=top;i++) System.out.println(a[i]); } } public Object peek() { if(isEmpty()) { System.out.println("The stack is empty"); return null; } else { System.out.println("The top element on the stack is:"); return a[top]; } } public int size() { top=top+1; return top; }
}
class StackArrayADTPgm17a{ public static void main(String args[]) throws IOException { int n,ch,len; Object item; System.out.println("Enter maximum size of the stack"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); n=Integer.parseInt(br.readLine()); ArrayStackADT s=new ArrayStackADT(n); while(true) { System.out.println("\nMenu:\n1.push\n2.pop\n3.display\n4.peek\n5.size\n6.exit\n"); System.out.println("enter your choice"); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: System.out.println("enter an element to be pushed"); item=br.readLine(); s.push(item); break;
case 2: s.pop();
25
break;
case 3: s.display(); break;
case 4: item=s.peek(); System.out.println(item); break;
case 5: len=s.size(); System.out.println("The size of the stack is:"+len); break;
case 6: System.exit(0); break; default:System.out.println("invalid choice"); break;} } }}
(17)(b)Queue ADT Array
import java.io.*;interface Queue{ public void insert(Object item); public void delete(); public void display(); public boolean isEmpty();}class ArrayQueueADT implements Queue{ int front,rear,i,max; Object item,a[]; ArrayQueueADT(int n) { a=new Object[n]; max=n; front=0; rear=-1; } public void insert(Object data) { if(rear==a.length-1)
26
System.out.println("The queue is full"); else { item=data; rear++; a[rear]=item; } } public boolean isEmpty() { if((front==0)&&(rear==-1)) return true; else return false; } public void delete() { if(isEmpty()) System.out.println("The queue is empty"); else { item=a[front]; if(front==rear) { front=0; rear=-1; } else front++; System.out.println("The deleted item is:"+item); } } public void display() { if(isEmpty()) System.out.println("The queue is empty"); else { System.out.println("The elements in the queue are:"); for(i=front;i<=rear;i++) System.out.println(a[i]); } }}
class QueueArrayADTPgm17b{ public static void main(String args[]) throws IOException { Object item;
27
int n,ch; System.out.println("Enter maximum size of the queue"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); n=Integer.parseInt(br.readLine()); ArrayQueueADT s=new ArrayQueueADT(n); while(true) { System.out.println("\nMenu:\n1.insert\n2.delete\n3.display\n4.exit\n"); System.out.println("enter your choice"); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: System.out.println("enter an element to be inserted"); item=br.readLine(); s.insert(item); break;
case 2: s.delete(); break;
case 3: s.display(); break; case 4: System.exit(0); break;
default:System.out.println("invalid choice"); break; } } }}
(18)(a) Write a java program that reads an infix expression, converts the expression topostfix form and then evaluates the postfix expression (use stack ADT).
class InfixToPostfix{java.util.Stack<Character> stk =new java.util.Stack<Character>();public String toPostfix(String infix){infix = "(" + infix + ")"; String postfix = "";for (int i = 0; i < infix.length(); i++){char ch, item;
28
ch = infix.charAt(i);if (isOperand(ch)) postfix = postfix + ch; if (ch == '(')stk.push(ch); if (isOperator(ch)) {item = stk.pop(); if (isOperator(item)){if (precedence(item) >= precedence(ch)){stk.push(item);stk.push(ch);}else{postfix = postfix + item;stk.push(ch);}}else{stk.push(item);stk.push(ch);}} if (ch == ')'){item = stk.pop();while (item != '('){postfix = postfix + item;item = stk.pop();}}} return postfix;} 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 '/'
29
if (c == '+' || c == '-') rank = 2;return rank;}
}class InfixToPostfix18{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));}
}
(18)(b)Evaluation of Postfix
class EvaluatePostfixExpression18b{public static void main(String args[]){String postfix = "5 6 2 + * 8 4 / -";java.util.Stack<Integer> stk =new java.util.Stack<Integer>();char ch;for (int i = 0; i < postfix.length(); i++){ch = postfix.charAt(i);if (isDigit(ch))stk.push(new Integer(Character.digit(ch, 10)));if (isOperator(ch)){int tmp1 = stk.pop();int tmp2 = stk.pop();int result = evaluate(tmp2, tmp1, ch);stk.push(result);}}System.out.println("Value of postfix expr = " + stk.pop());}static boolean isDigit(char c){return (c >= '0' && c <= '9');}static boolean isOperator(char c){ return (c == '+' || c == '-' || c == '*' || c == '/');}static int evaluate(int a, int b, char op){int res = 0;
30
switch (op){case '+': res = (a + b); break;case '-': res = (a - b); break;case '*': res = (a * b); break;case '/': res = (a / b); break;}return res;}
}
(19) Write a java program that determines whether parenthetic symbols ( ), { } and < >are nested correctly in a string of characters (use stack ADT).
import java.io.*;import java.util.*;class Stack{ int top,size; char a[],data; Stack(int x) { size=x; a=new char[size]; top=-1; } public boolean isEmpty() { if(top==-1) return true; else return false; } public char pop() { return a[top--]; } public void push(char ele) { top++; a[top]=ele; }}class ParentheticSymbolsPgm19{ public static void main(String args[]) throws IOException { char ch,symb; int i,count=0,count2=0,len; BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
31
System.out.println("enter a string of characters"); String str=br.readLine(); len=str.length(); Stack s=new Stack(len); for(i=0;i<len;i++) { ch=str.charAt(i); if(ch=='('||ch=='{'||ch=='[') s.push(ch); if(ch==')'||ch=='}'||ch==']') { if(s.isEmpty()) count++; else { symb=s.pop(); if((symb=='['&&ch==']')||(symb=='{'&&ch=='}')||(symb=='('&&ch==')')) count2=0; else count++; } } } if((count==0)&&(s.isEmpty())) System.out.println("The string is nested correctly"); else System.out.println("The string is nested incorrectly"); }}
(20) Write a java program that uses both stack and queue to test whether the givenstring is a palindrome.
import java.util.Stack;class PalindromeStackADT20a{public static void main(String args[]){String str = "MALAYALAM";if (isPalindrome(str))System.out.println(str + " is a Palindrome");elseSystem.out.println(str + " is not a Palindrome");}static boolean isPalindrome(String str){Stack<Character> stk = new Stack<Character>();for (int i = 0; i < str.length(); i++)stk.push(str.charAt(i));for (int i = 0; i < str.length() / 2; i++)
32
if (str.charAt(i) != stk.pop()) return false;return true;}
}
(20)(b)Palindrome using Queue ADT
import java.util.LinkedList;class PalindromeQueueADT20b{public static void main(String args[]){String str = "AMMA";if (isPalindrome(str))System.out.println(str + " is a Palindrome");elseSystem.out.println(str + " is not a Palindrome");}static boolean isPalindrome(String str){LinkedList<Character> que = new LinkedList<Character>();int n = str.length();for (int i = 0; i < n; i++)que.addLast(str.charAt(i));for (int i = n - 1; i > n / 2; i--)if (str.charAt(i) != que.removeFirst()) return false;return true;}}
(21) Write Java programs to implement the following using a singly linked list.(a)Stack ADT Linked List
class Node{ int data;Node next; Node( int d ) { data = d; }
}class LinkedStack{Node top;Node p; public void push(int item) {p = new Node(item); p.next = top; top = p;
33
}public Node pop(){if (isEmpty()){System.out.println("Stack is empty");return null;}Node tmp = top; top = tmp.next; return tmp; }
public void displayStack(){p = top; // p refers to topSystem.out.print("\nContents of Stack: [ ");while (p != null) {System.out.print(p.data + " ");p = p.next;}System.out.println("]");}public boolean isEmpty(){ return (top == null); }
}class StackADT21a{public static void main(String[] args){LinkedStack stk = new LinkedStack();Node item;stk.push(20);stk.push(35);stk.push(40);stk.displayStack();item = stk.pop();if( item != null ){System.out.println("Popped item: " + item.data);stk.displayStack();}stk.push(65); // insert 65, 70, 75stk.push(70);stk.push(75);stk.displayStack();item = stk.pop();
34
if( item != null ){System.out.println("Popped item: "+ item.data);stk.displayStack();}stk.push(90); // insert 90stk.displayStack();}
}
(21)(b)Queue ADT LinkedList
class LinkedQueue{class Node{Object data;Node next;Node(Object item) { data = item; }}Node front, rear;int count;public void insert(Object item){Node p = new Node(item);if (front == null) {front = rear = p;rear.next = null;}if (front == rear) {rear = p;front.next = rear;rear.next = null;}else{rear.next = p; rear = p; rear.next = null;}count++; }public Object remove(){if (isEmpty())
35
{ System.out.println("Q is empty"); return null;}Object item = front.data;front = front.next;count--; 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();}
}class QueueADTLinkedList21b{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');
36
System.out.println("delete(): " + q.remove());q.display();System.out.println("size(): " + q.size());}
}
(22)write jav aprograms to implement the dequeue(doubly ended queue) ADT using(a) Array
class ArrayDeque{private int maxSize;private Object[] que;private int first;private int last;private int count; // current number of items in dequepublic ArrayDeque(int s) // constructor{maxSize = s;que = new Object[maxSize];first = last = -1;count = 0;}public void insertLast(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 deleteLast(){ 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 insertFirst(Object item){if(count == maxSize)
37
{ 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 deleteFirst(){ if(count == 0){System.out.println("Deque is empty");return(' ');}Object item = que[first];que[first] = ' ';if(first == maxSize-1) first = 0;elsefirst = (first+1) % maxSize;count--;if(count == 0)first = last = -1;return(item);}void display(){ System.out.println("----------------------------");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(){ return (count == 0); }public boolean isFull() {return (count == maxSize); }
}class DequeueADTArray22a
38
{public static void main(String[] args){ArrayDeque q = new ArrayDeque(6);q.insertLast('A'); q.insertLast('B');q.insertLast('C');q.insertLast('D');System.out.println("deleteFirst():"+q.deleteFirst());q.display();q.insertLast('E'); q.display();System.out.println("deleteLast():"+q.deleteLast());System.out.println("deleteLast():"+q.deleteLast());q.display();q.insertFirst('P'); q.insertFirst('Q'); q.insertFirst('R'); q.display();q.deleteFirst(); q.display(); q.insertFirst('X'); q.display(); q.insertLast('Y'); q.display(); q.insertLast('Z'); q.display(); }
}
(22)(c) Doubly Linked List
class LinkedDeque{public class DequeNode{DequeNode prev;Object data;DequeNode next;DequeNode(Object item){data = item;} }private DequeNode first, last;private int count;public void addFirst(Object item){if (isEmpty())first = last = new DequeNode(item);else{DequeNode tmp = new DequeNode(item);tmp.next = first;first.prev = tmp;first = tmp;
39
}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(){
40
if (!isEmpty()) return (first.data);else return null;}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("]");}
}class DQueueADTDLL22c{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());}
}
(23) Write a java program to implement priority queue ADT.
41
class Node{ String data;int prn; Node next; Node( String str, int p ) { data = str;prn = p;}
}class LinkedPriorityQueue{Node head; public void insert(String item, int pkey) {Node newNode = new Node(item, pkey); int k;if( head == null ) k = 1;else if( newNode.prn < head.prn ) k = 2;elsek = 3;switch( k ){ case 1: head = newNode; head.next = null;break;case 2: Node oldHead = head; head = newNode;newNode.next = oldHead;break;case 3: Node p = head; Node prev = p;Node nodeBefore = null;while( p != null ){if( newNode.prn < p.prn ){nodeBefore = p;break;}else{prev = p; p = p.next; }} newNode.next = nodeBefore;
42
prev.next = newNode;} } 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;System.out.print("\nQueue: ");while( p != null ){System.out.print(p.data+"(" +p.prn+ ")" + " ");p = p.next; }System.out.println();}public boolean isEmpty(){return (head == null); }public Node peek() {return head; }
}class PriorityQueueADT23{public static void main(String[] args){LinkedPriorityQueue pq = new LinkedPriorityQueue(); Node item;pq.insert("Babu", 3);pq.insert("Nitin", 2);pq.insert("Laxmi", 2);pq.insert("Kim", 1);pq.insert("Jimmy", 3);pq.displayList();item = pq.delete();
43
if (item != null)System.out.println("delete():" + item.data+ "(" + item.prn + ")");pq.displayList();pq.insert("Scot", 2);pq.insert("Anu", 1);pq.insert("Lehar", 4);pq.displayList();}
}
(24) Write a Java program to perform the following operations:a) Insert an element into a binary search tree.b) Delete an element from a binary search tree.c) Search for a key element in a binary search tree.
class BSTNode{int data;BSTNode left;BSTNode right;BSTNode( int d ) { data = d; }
}class BinarySearchTree{public BSTNode insertTree(BSTNode p, int key) {if( p == null )p = new BSTNode(key);else if( key < p.data)p.left = insertTree( p.left, key);else p.right = insertTree( p.right, key);return p; }public BSTNode search(BSTNode root, int key){BSTNode p = root; while( p != null ){ if( key == p.data )return p;else if( key < p.data ) p = p.left;else p = p.right;}
44
return null;}
public BSTNode deleteTree(BSTNode root, int key){BSTNode p;BSTNode parent = root; BSTNode inorderSucc; if(root == null){ System.out.println("Tree is empty");return null;}p = root;while( p != null && p.data != key){ parent = p;if( key < p.data) p = p.left;else p = p.right;}if( p == null ){ System.out.println("\n Node " + key + " not found for deletion");return null;}if(p.left != null && p.right != null) { parent = p;inorderSucc = p.right;while(inorderSucc.left != null){parent = inorderSucc;inorderSucc = inorderSucc.left;}p.data = inorderSucc.data;p = inorderSucc;}if(p.left == null && p.right == null) {if( parent.left == p ) parent.left = null;else parent.right = null;}if(p.left == null && p.right != null) {if(parent.left == p) parent.left = p.right;
45
else parent.right = p.right;}if(p.left != null && p.right == null) {if(parent.left == p)parent.left = p.left;else parent.right = p.left;}return root;}public void inorder(BSTNode p) { if( p != null ){ inorder(p.left);System.out.print(p.data + " ");inorder(p.right);}}public void preorder(BSTNode p){ if( p != null ){ System.out.print(p.data + " ");preorder(p.left);preorder(p.right);}}public void postorder(BSTNode p){ if( p != null ){ postorder(p.left);postorder(p.right);System.out.print(p.data + " ");}}
} class BinarySearchTreeDemo{public static void main(String args[]){int arr[] = { 45, 25, 15, 10, 20, 30, 65, 55, 50, 60, 75, 80 };BinarySearchTree bst = new BinarySearchTree();BSTNode root = null;for (int i = 0; i < arr.length; i++)root = bst.insertTree(root, arr[i]);BSTNode root2 = root;
46
int key = 66;BSTNode item = bst.search(root2, key);if (item != null)System.out.print("\n item found: " + item.data);else System.out.print("\n Node " + key + " not found");System.out.print("\n Inorder: ");bst.inorder(root);System.out.print("\n Preorder: ");bst.preorder(root);System.out.print("\n Postorder: ");bst.postorder(root);key = 55;bst.deleteTree(root, key);System.out.print("\n Inorder, after deletion of " + key + ": ");bst.inorder(root);key = 44;bst.insertTree(root, key);System.out.print("\n Inorder, after insertion of " + key + ": ");bst.inorder(root);}
}
(25)Write a Java program to implement all the functions of a dictionary (ADT) usingHashing.
class Entry{public String key;public String element;public Entry(String k, String e){key = k;element = e;}
}class HashTable{Entry[] hashArray;int size;int count;public HashTable(int s){size = s;count = 0;hashArray = new Entry[size];}int hashFunc(String theKey){int hashVal = 0;
47
for (int i = 0; i < theKey.length(); i++)hashVal = 37 * hashVal + (int)theKey.charAt(i);hashVal = hashVal % size;if (hashVal < 0)hashVal = hashVal + size;return hashVal;}public void insert(String theKey, String str){if (!isFull()){int hashVal = hashFunc(theKey);while (hashArray[hashVal] != null){++hashVal;hashVal %= size; }hashArray[hashVal] = new Entry(theKey, str);count++;}elseSystem.out.println("Table is full");}public Entry delete(String theKey){if (!isEmpty()){int hashVal = hashFunc(theKey);while (hashArray[hashVal] != null){if (hashArray[hashVal].key == theKey){Entry tmp = hashArray[hashVal];hashArray[hashVal] = null;count--;return tmp;}++hashVal; hashVal %= size;}return null;}elseSystem.out.println("Table is empty");return null;}public Entry search(String theKey){int hashVal = hashFunc(theKey);while (hashArray[hashVal] != null)
48
{if (hashArray[hashVal].key == theKey)return hashArray[hashVal];++hashVal;hashVal %= size;}return null;}public void displayTable(){System.out.println("<< Dictionary Table >>\n");for (int i = 0; i < size; i++){if (hashArray[i] != null)System.out.println(hashArray[i].key + "\t" + hashArray[i].element);}}public boolean isEmpty(){return count == 0;}public boolean isFull(){return count == size;}public int currentSize(){return count;}
}
class Dictionary{public static void main(String[] args){HashTable ht = new HashTable(19); ht.insert("man", "gentleman");ht.insert("watch", "observe");ht.insert("hope", "expect");ht.insert("arrange", "put together");ht.insert("run", "sprint");ht.insert("wish", "desire");ht.insert("help", "lend a hand");ht.insert("insert", "put in");ht.insert("count", "add up");ht.insert("format", "arrangement");ht.displayTable();String word = "wish";Entry item = ht.search(word);if (item != null)
49
System.out.println("found: " + item.key + "\t" + item.element);elseSystem.out.println(word + " not found");word = "hope";item = ht.delete(word);if (item != null)System.out.println("deleted: " + item.key + "\t" + item.element);elseSystem.out.println(word + " not found - no deletion");System.out.println("size: " + ht.currentSize());}
}
(25)(b) Dictionary operations using java.util.Hashtable
import java.util.*;class HashtableDemo{public static void main(String[] args){Hashtable<String, String> htab = new Hashtable<String, String>();htab.put("man", "gentleman");htab.put("watch", "observe");htab.put("hope", "expect");htab.put("arrange", "put together");htab.put("run", "sprint");htab.put("wish", "desire");htab.put("help", "lend a hand");htab.put("insert", "put in");htab.put("count", "add up");htab.put("format", "arrangement");System.out.println(htab); // Display the table items System.out.println("get(hope): " + htab.get("hope"));System.out.println("remove(arrange): " + htab.remove("arrange"));System.out.println("remove(help): " + htab.remove("help"));System.out.println(htab.entrySet());}
}
(26) Write a Java program to implement circular queue ADT using an array.
import java.io.*;interface CircularQueue{ public void insert(Object ele); public void delete(); public void display();}class CircularQueueADT implements CircularQueue
50
{ int front,rear,MAX_SIZE; Object a[],x; CircularQueueADT(int n) { front=rear=-1; MAX_SIZE=n; a=new Object[MAX_SIZE]; } public void insert(Object x) { if((rear==front-1)||(front==0&&rear==MAX_SIZE-1)) System.out.println("The circular queue is full"); else if(rear==-1) { front++; rear++; a[rear]=x; } else if((rear==MAX_SIZE-1)&&front!=0) { rear=0; a[rear]=x; } else { rear++; a[rear]=x; } } public void delete() { if(front==-1&&rear==-1) { System.out.print("circular queue is empty"); } else { if(front==rear) { x=a[front]; front=rear=-1; System.out.println("the deleted item is:"+x); } else if(front==MAX_SIZE-1) { x=a[front]; front=0; System.out.println("the deleted item is:"+x); }
51
else { x=a[front]; front++; System.out.println("The deleted item is:"+x); } } } public void display() { int i; if(front==-1) System.out.println(" circular queue is empty"); else if(front<=rear) { System.out.println("the elements in the circular queue are:"); for(i=front;i<=rear;i++) System.out.println(a[i]); } else { System.out.println("The elements in the circular queue are:"); for(i=0;i<=rear;i++) System.out.println(a[i]); for(i=front;i<MAX_SIZE;i++) System.out.println(a[i]); } }}
class CircularQueueArrayADTPgm26{ public static void main(String args[]) throws IOException { int n,choice; Object insEle; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the size of the circular queue"); n=Integer.parseInt(br.readLine()); CircularQueueADT s=new CircularQueueADT(n); while(true) { System.out.println("__________"); System.out.println("Menu:\n1.insert\n2.delete\n3.display\n4.exit"); System.out.println("_________"); System.out.println("enter your choice"); choice=Integer.parseInt(br.readLine()); switch(choice) { case 1:
52
System.out.println("enter the element to be inserted onto the circular queue"); insEle=br.readLine(); s.insert(insEle); break;
case 2: s.delete(); break; case 3: s.display(); break; case 4: System.out.println("you are exited"); System.exit(0); break;
default:System.out.println("invalid choice"); break; } } }}
(27) Write Java programs that use recursive and non-recursive functions to traverse thegiven binary tree ina) Preorderb) In order andc) Post order.
class Node{ Object data;Node left;Node right;Node( Object d ) { data = d; }}class BinaryTree{Object tree[];int maxSize;java.util.Stack<Node> stk = new java.util.Stack<Node>();BinaryTree( Object a[], int n ) { maxSize = n;tree = new Object[maxSize];
53
for( int i=0; i<maxSize; i++ )tree[i] = a[i];}public Node buildTree( int index ){ Node p = null;if( tree[index] != null ){ p = new Node(tree[index]);p.left = buildTree(2*index+1);
p.right = buildTree(2*index+2);}return p;}public void inorder(Node p){if( p != null ){inorder(p.left);System.out.print(p.data + " ");inorder(p.right);}}public void preorder(Node p){if( p != null ){System.out.print(p.data + " ");preorder(p.left);preorder(p.right);}}public void postorder(Node p){if( p != null ){postorder(p.left);postorder(p.right);System.out.print(p.data + " ");}}public void preorderIterative(Node p){if(p == null ){ System.out.println("Tree is empty");return;}stk.push(p);while( !stk.isEmpty() )
54
{p = stk.pop();if( p != null ){System.out.print(p.data + " ");stk.push(p.right);stk.push(p.left);}}}public void inorderIterative(Node p){if(p == null ){ System.out.println("Tree is empty");return;}
while( !stk.isEmpty() || p != null ){if( p != null ){ stk.push(p); p = p.left;}else{p = stk.pop();System.out.print(p.data + " "); p = p.right; }}}public void postorderIterative(Node p){if(p == null ){ System.out.println("Tree is empty");return;}Node tmp = p;while( p != null ){while( p.left != null ){ stk.push(p);p = p.left;}while( p != null && (p.right == null || p.right == tmp )){ System.out.print(p.data + " "); tmp = p;
55
if( stk.isEmpty() )return;p = stk.pop();}stk.push(p);p = p.right;}}}
class BinaryTreeDemo{public static void main(String args[]){Object arr[] = {'E', 'C', 'G', 'A', 'D', 'F', 'H',null,'B', null, null, null, null,null, null, null, null, null, null};BinaryTree t = new BinaryTree( arr, arr.length );Node root = t.buildTree(0); System.out.print("\n Recursive Binary Tree Traversals:");System.out.print("\n inorder: ");t.inorder(root);System.out.print("\n preorder: ");
t.preorder(root);System.out.print("\n postorder: ");t.postorder(root);System.out.print("\n Non-recursive Binary Tree Traversals:");System.out.print("\n inorder: ");t.inorderIterative(root);System.out.print("\n preorder: ");t.preorderIterative(root);System.out.print("\n postorder: ");t.postorderIterative(root);}}
(28) Write Java programs for the implementation of dfs and bfs for a given graph.
(a)DFS
class Node{ int label;Node next;Node( int b ) {label = b; }
}class Graph{ int size;
56
Node adjList[];int mark[];Graph(int n) // constructor{ size = n;adjList = new Node[size];mark = new int[size];}public void createAdjList(int a[][]){Node p; int i, k;for (i = 0; i < size; i++){p = adjList[i] = new Node(i); for (k = 0; k < size; k++){if (a[i][k] == 1){p.next = new Node(k);p = p.next;}}}}public void dfs(int head){Node w; int v;mark[head] = 1;System.out.print(head + " ");w = adjList[head];while (w != null){v = w.label;if (mark[v] == 0) dfs(v);w = w.next;}}
}class DfsDemo{public static void main(String[] args){Graph g = new Graph(5); int a[][] = { {0,1,0,1,1}, {1,0,1,1,0}, {0,1,0,1,1},{1,1,1,0,0}, {1,0,1,0,0}};g.createAdjList(a);g.dfs(0); // starting node to dfs is0 (i.e., A)}
}
57
(28)(b)BFS
class Node{ int label;Node next;Node( int b ){ label = b; }
}class Graph{ int size;Node adjList[];int mark[];Graph(int n){ size = n;adjList = new Node[size];mark = new int[size];}public void createAdjList(int a[][]){ Node p;int i, k;for( i = 0; i < size; i++ ){ p = adjList[i] = new Node(i);for( k = 0; k < size; k++ ){ if( a[i][k] == 1 ){ p.next = new Node(k);p = p.next;}}}}public void bfs(int head){ int v;Node adj;Queue q = new Queue(size);v = head;mark[v] = 1;System.out.print(v + " ");q.qinsert(v);while( !q.IsEmpty() ) {
58
v = q.qdelete();adj = adjList[v];while( adj != null ){ v = adj.label;if( mark[v] == 0 ){ q.qinsert(v);mark[v] = 1;System.out.print(v + " ");}adj = adj.next;}}}
} class Queue{ private int maxSize;private int[] que;private int front;private int rear;private int count;public Queue(int s){ maxSize = s;que = new int[maxSize];front = rear = -1;}public void qinsert(int item){ if( rear == maxSize-1 )System.out.println("Queue is Full");else { rear = rear + 1;que[rear] = item;if( front == -1 ) front = 0;}}public int qdelete(){ int item;if( IsEmpty() ){ System.out.println("\n Queue is Empty");return(-1);}item = que[front];if( front == rear )
59
front = rear = -1;elsefront = front+1;return(item);}public boolean IsEmpty(){ return( front == -1 ); }
} class BfsDemo{public static void main(String[] args){ Graph g = new Graph(5);int a[][] = { {0,1,0,1,1}, {1,0,1,1,0}, {0,1,0,1,1},{1,1,1,0,0}, {1,0,1,0,0}};g.createAdjList(a);g.bfs(0);}
}
(29) Write Java programs for implementing the following sorting methods:a) Bubble sort d) Quick sort g) Radix sortb) Selection sort e) Merge sort h) Binary tree sortc) Insertion sort f) Heap sort
(a)Bubble sort
import java.io.*;class BubbleSort{int i,j;int a[];void bubSort(int ele[],int n) { a=ele; for(i=0;i<n;i++) {for(j=i+1;j<n;j++)
{ if(a[i]>a[j]) { int temp; temp=a[i]; a[i]=a[j]; a[j]=temp; } } }
60
}}class BubbleSortPgm29a{ public static void main(String args[])throws IOException { BubbleSort bs=new BubbleSort(); int n,i; int item[]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter no.of elements"); n=Integer.parseInt(br.readLine()); item=new int[n]; System.out.println("enter elements"); for(i=0;i<n;i++) item[i]=Integer.parseInt(br.readLine()); System.out.println("Bubble Sort"); System.out.println("elements before sorting"); for (i = 0; i < n; i++) System.out.print(item[i] + " "); bs.bubSort(item,n); System.out.println("\nelements after sorting "); for (i = 0; i < n; i++) System.out.print(item[i] + " ");
}}
(29)(b)Selection Sort
import java.io.*;class SelectionSort{ int i,j,min; int temp; int a[]; void selSort(int ele[],int n) { a=ele; for(i=0;i<n;i++) { min=i; for(j=i+1;j<n;j++) { if(a[j]<a[min]) min=j; } temp=a[i]; a[i]=a[min]; a[min]=temp;
61
} }}class SelectionSortPgm29b{ public static void main(String args[])throws IOException { SelectionSort s=new SelectionSort(); int n,i; int item[]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter no.of elements"); n=Integer.parseInt(br.readLine()); item=new int[n]; System.out.println("enter elements"); for(i=0;i<n;i++) item[i]=Integer.parseInt(br.readLine()); System.out.println("Selection Sort"); System.out.println("elements before sorting"); for (i = 0; i < n; i++) System.out.print(item[i] + " "); s.selSort(item,n); System.out.println("\nelements after sorting"); for (i = 0; i < n; i++) System.out.print(item[i] + " "); }}
(29)(c)Insertion Sort
import java.io.*;class InsertionSort{ int i,j,min; int temp; int a[]; void insertSort(int ele[],int n) { int i, j,tmp; a=ele; for (i = 1; i < n; i++) { tmp = a[i]; for (j = i; j > 0 && (tmp < a[j - 1]); j--) { a[j] = a[j - 1]; } a[j] = tmp; }
62
}}class InsertionSortPgm29c{ public static void main(String args[])throws IOException { InsertionSort ins=new InsertionSort(); int n,i; int item[]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter no.of elements"); n=Integer.parseInt(br.readLine()); item=new int[n]; System.out.println("enter elements"); for(i=0;i<n;i++) item[i]=Integer.parseInt(br.readLine()); System.out.println("insertion sort"); System.out.println("elements before sorting"); for (i = 0; i < n; i++) System.out.print(item[i] + " "); ins.insertSort(item,n); System.out.println("\nelements after sorting"); for (i = 0; i < n; i++) System.out.print(item[i] + " ");}}
(29)(d)Quick Sort
import java.io.*;class QuickSort{public void quick_srt(int array[], int low, int n){int lo = low;int hi = n;if (lo >= n){return;}int mid = array[(lo + hi) / 2];while (lo < hi){while (lo < hi && array[lo] < mid){lo++;}while (lo < hi && array[hi] > mid){hi--;}if (lo < hi)
63
{int T = array[lo];array[lo] = array[hi];array[hi] = T;}}if (hi < lo){int T = hi;hi = lo;lo = T;}quick_srt(array, low, lo);quick_srt(array, lo == low ? lo + 1 : lo, n);}
}
class QuickSortPgm29d{public static void main(String a[])throws IOException{QuickSort qs = new QuickSort();int n, i;int item[];BufferedReader br = new BufferedReader(new InputStreamReader(System.in));System.out.println("enter no.of elements");n = Integer.parseInt(br.readLine());item = new int[n];System.out.println("enter elements");for (i = 0; i < n; i++)item[i] = Integer.parseInt(br.readLine());System.out.println("Quick Sort");System.out.println("elements before sorting");for (i = 0; i < item.length; i++)System.out.print(item[i] + " ");qs.quick_srt(item, 0, item.length - 1);System.out.println("\nelements after sorting");for (i = 0; i < item.length; i++)System.out.print(item[i] + " ");}
}
(29)(e)Merge Sort
import java.io.*;;class MergeSort{void mergeSort_srt(int array[], int lo, int n){int low = lo;
64
int high = n;if (low >= high){return;}int middle = (low + high) / 2;mergeSort_srt(array, low, middle);mergeSort_srt(array, middle + 1, high);int end_low = middle;int start_high = middle + 1;while ((lo <= end_low) && (start_high <= high)){if (array[low] < array[start_high]){low++;}else{int Temp = array[start_high];for (int k = start_high - 1; k >= low; k--){array[k + 1] = array[k];}array[low] = Temp;low++;end_low++;start_high++;}}
}}class MergeSortPgm29e{ public static void main(String a[])throws IOException { MergeSort ms=new MergeSort(); int n,i; int item[]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter no.of elements"); n=Integer.parseInt(br.readLine()); item=new int[n]; System.out.println("enter elements"); for(i=0;i<n;i++) item[i]=Integer.parseInt(br.readLine()); System.out.println("Merge Sort"); System.out.println("elementss before sorting"); for (i = 0; i < item.length; i++) System.out.print(item[i] + " ");
65
ms.mergeSort_srt(item, 0, item.length - 1); System.out.println("\nelements after sorting"); for (i = 0; i < item.length; i++) System.out.print(item[i] + " "); }}
(29(f)Heap Sort
import java.io.*;class HeapSort{public void fnSortHeap(int array[], int arr_ubound){int i, o;int lChild, rChild, mChild, root, temp;root = (arr_ubound - 1) / 2;for (o = root; o >= 0; o--){for (i = root; i >= 0; i--){lChild = (2 * i) + 1;rChild = (2 * i) + 2;if ((lChild <= arr_ubound) && (rChild <= arr_ubound)){if (array[rChild] >= array[lChild])mChild = rChild;elsemChild = lChild;}else{if (rChild > arr_ubound)mChild = lChild;elsemChild = rChild;}if (array[i] < array[mChild]){temp = array[i];array[i] = array[mChild];array[mChild] = temp;}}}temp = array[0];array[0] = array[arr_ubound];array[arr_ubound] = temp;return;}
}66
class HeapSortPgm29f{public static void main(String a[])throws IOException{int n, i;int item[];HeapSort hs = new HeapSort();BufferedReader br = new BufferedReader(new InputStreamReader(System.in));System.out.println("enter no.of elements");n = Integer.parseInt(br.readLine());item = new int[n];System.out.println("enter elements");for (i = 0; i < n; i++)item[i] = Integer.parseInt(br.readLine());System.out.println("Heap Sort");System.out.println("elements before sorting");for (i = 0; i < item.length; i++)System.out.print(item[i] + " ");for (i = item.length; i > 1; i--)hs.fnSortHeap(item, i - 1);System.out.println("\nelements after sorting");for (i = 0; i < item.length; i++)System.out.print(item[i] + " ");}
}
(29)(g)Radix Sort
import java.util.*;class RadixSortDemo{public static void main(String[] args) {int[] a = { 3305, 99, 52367, 1252, 0110, 12345, 7, 35, 7509, 3, 345 };radixSort(a, 10, 5);System.out.println("Sorted list: ");for (int i = 0; i < a.length; i++)System.out.print(a[i] + " ");
}static void radixSort(int[] arr, int radix, int maxDigits) {int d, j, k, m, divisor;LinkedList[] q= new LinkedList[radix];for (d = 0; d < radix; d++)q[d] = new LinkedList();divisor = 1;for (d = 1; d <= maxDigits; d++) {for (j = 0; j < arr.length; j++){m = (arr[j] / divisor) % radix;
67
q[m].addLast(new Integer(arr[j]));}divisor = divisor * radix;for (j = k = 0; j < radix; j++){while (!q[j].isEmpty())arr[k++] = (Integer)q[j].removeFirst();}}
}}
(29)(h)Binary Tree Sort
import java.io.*;class Node{Node left;Node right;int value;public Node(int value){this.value = value;}
}
class BinaryTreeSort{public void insert(Node node, int value){if (value < node.value){if (node.left != null)insert(node.left, value);elsenode.left = new Node(value);}else if (value > node.value){if (node.right != null)insert(node.right, value);elsenode.right = new Node(value);}}public void printInOrder(Node node){if (node != null){
68
printInOrder(node.left);System.out.print(node.value+" ");printInOrder(node.right);}}
}
class BinaryTreeSortPgm29h{public static void main(String args[])throws IOException{int n, i;int item[];BufferedReader br = new BufferedReader(new InputStreamReader(System.in));System.out.println("enter no.of elements");n = Integer.parseInt(br.readLine());item = new int[n];System.out.println("enter elements");for (i = 0; i < n; i++)item[i] = Integer.parseInt(br.readLine());System.out.println("Binary Tree Sort");System.out.println("elements before sorting");for (i = 0; i < n; i++)System.out.print(item[i] + " ");Node rootnode = new Node(item[0]);BinaryTreeSort bts=new BinaryTreeSort();for (i = 1; i < item.length; i++)bts.insert(rootnode, item[i]); System.out.println("\nelements after sorting");bts.printInOrder(rootnode);}
}
30)write a java program to perform the following operations
a)Insertion into a B-tree
b)Searching in a B-tree
class BTree{final int MAX = 4;final int MIN = 2;class BTNode {int count;int key[] = new int[MAX+1];BTNode child[] = new BTNode[MAX+1];}BTNode root = new BTNode();class Ref
69
{ int m; } 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;}}boolean pushDown( int val, BTNode node, Ref p, BTNode c ){Ref k = new Ref();if ( node == null ){p.m = val;c = null;return true;}else{if ( searchNode( val, node, k ) )System.out.println("Key already exists.");if ( pushDown( val, node.child[k.m], p, c ) ){if ( node.count < MAX ){pushIn( p.m, c, node, k.m );return false;}else{split( p.m, c, node, k.m, p, c );return true;}}return false;}}
BTNode searchTree( int val, BTNode root, Ref pos ){if ( root == null )
70
return null ;else{if ( searchNode( val, root, pos ) )return root;elsereturn searchTree( val, root.child[pos.m], pos );}}
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;elsereturn 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;elsemid = MIN + 1;
71
newnode = new BTNode();for ( i = mid+1; i <= MAX; i++ ){newnode.key[i-mid] = node.key[i];newnode.child[i-mid] = node.child[i];}newnode.count = MAX - mid;node.count = mid;if ( k <= MIN )pushIn ( val, c, node, k );elsepushIn ( val, c, newnode, k-mid ) ;y.m = node.key[node.count];newnode.child[0] = node.child[node.count] ;node.count-- ;}
void displayTree(){display( root );}
void display( BTNode root ){int i;if ( root != null ){for ( i = 0; i < root.count; i++ ){display( root.child[i] );System.out.print( root.key[i+1] + " " );}display( root.child[i] );}}} class BTreeDemo{public static void main( String[] args ){BTree bt = new BTree();int[] arr = { 11, 23, 21, 12, 31, 18, 25, 35, 29, 20, 45,27, 42, 55, 15, 33, 36, 47, 50, 39 };for ( int i = 0; i < arr.length; i++ )bt.insertTree( arr[i] );System.out.println("B-Tree of order 5:");bt.displayTree();}}
72