You are on page 1of 63

Advanced Problem Solving Lab Manual INDEX

Sl. NO 1 Name of the Program

M. Tech(IT)

Page No. 2

3 4 5 6

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. 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. Write a Java Program that reads a line of integers, and then displays each integer, and the sum of all the integers (use StringTokenizer class) Write a Java Program to illustrate Method Overloading Write a Java program for sorting a given list of names in ascending order. Write a Java program to implement the matrix ADT using a class. The operations supported by this ADT are: (a) Reading a Matrix (b) Printing a Matrix (c) Addition of Matrix (d) Subtraction of Matrix (e) Multiplication of Matrix Write a Java program that uses a recursive function to compute ncr. ( Note: n and r values are given). Write a java program to make frequency count of words in a given text Write a Java program that reads a 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. 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. Write a Java program that implements the Stack ADT Develop an applet in java that receives an integer in one text filed and computes its factorial value and returns it in another text field. When the button named Compute is clicked. Write a Java program that works as a simple calculator. Use the Grid layout to arrange buttons for this digits and for the +,-,*,/,% operations. Add a text filed to display the result. Write a java program for handling mouse events. Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication. Write a java program that creates user interface to perform integer division. The user enters two numbers in the text fields Num1 and Num2. The division of two numbers is displayed in the result field when the divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a Number format exception. If Num2 were Zero, the program would throw an Arithmetic Exception display the exception in a message dialog box.

4 5 6

7 8 9

10 11 12

13

14 15 16

1|Page

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual


17 Write a java program that illustrates the following a) Creation of simple package. b) Accessing a package. c) Implementing interfaces. Write a java program that illustrates the following a) Handling predefined exceptions b) Handling user defined exceptions Write Java programs that use both recursive and non-recursive functions for implementing the following searching methods: a) Linear search b) Binary search Write Java programs to implement the Queue ADT using an array. Write Java programs to implement the following using a singly linked list. a) Stack ADT b) Queue ADT Write Java programs to implement the deque (double ended queue) ADT using

M. Tech(IT)

18

19

20 21

22

23 24 25

Write a java program to implement priority queue ADT. Write a java program to implement priority queue ADT.

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.
Write a Java program to implement all the functions of a dictionary (ADT) using Hashing. Write a Java program to implement circular queue ADT using an array. Write Java programs that use recursive and non-recursive functions to traverse the given binary tree in a) Preorder b) Inorder and c) Postorder. Write Java programs for the implementation of bfs and dfs for a given graph. Write Java programs for implementing the following sorting methods: a) Bubble sort d) Quick sort g) Radix sort b) Selection sort e) Merge sort h) Binary tree sort c) Insertion sort f) Heap sort Write a java program that uses recursive functions a. To create a binary search tree. b. To count the number of leaf nodes. c. To copy the above binary search tree.

26 27 28

29 30

31

2|Page

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 1

M. Tech(IT)

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 Qp { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a value:"); int a = Integer.parseInt(br.readLine()); System.out.println("Enter b value:"); int b = Integer.parseInt(br.readLine()); System.out.println("Enter c value:"); int c = Integer.parseInt(br.readLine()); double d=(b*b)-(4*a*c); if(d>0) { System.out.println("Roots are real and unequal"); double r1=(-b+Math.sqrt(d))/(2*a); double r2=(-b-Math.sqrt(d))/(2*a); System.out.println(r1); System.out.println(r2); } else if(d<0) { System.out.println("Roots are imaginary and don't have any real solutions"); } else { System.out.println("Roots are real and equal"); double r1=-b/(2*a); double r2=-b/(2*a); System.out.println(r1); System.out.println(r2); } } 3|Page Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual } Program 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.

M. Tech(IT)

Using Non-Recursive function class Fibn { int fibnr(int n) { int fir=1; int sec=1; int temp=0; for(int i=(n-2);i>0;i--) { temp=fir+sec; fir=sec; sec=temp; } return(temp); }

public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Fibn f = new Fibn(); System.out.println("Enter n value:"); int n = Integer.parseInt(br.readLine()); int res=f.fibnr(n); System.out.println(n + "value of series is"+res); } }

4|Page

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

Program 3 Write a Java Program that reads a line of integers, and then displays each integer, and the sum of all the integers (use StringTokenizer class) import java.io.*; import java.util.*; class strtokenizer { public static void main(String argv[])throws IOException { int sum = 0; DataInputStream d = new DataInputStream(System.in); System.out.println("Enter String of Integers"); String str = d.readLine(); StringTokenizer st = new StringTokenizer(str," "); System.out.println("The Inputted Integers are "); while(st.hasMoreTokens()) { int n = Integer.parseInt(st.nextToken()); System.out.print(n+","); sum = sum+n; } System.out.println("\nSum of all Integers are "+sum); } }

5|Page

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 4 Write a Java Program to illustrate Method Overloading

M. Tech(IT)

6|Page

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 5

M. Tech(IT)

Write a Java program for sorting a given list of names in ascending order. class ascname { public static void main(String args[]) { String str[]={"Abc","Xyz","Bcd","Pqr"}; int l=str.length; for(int i=0;i<l;i++) { for(int j=i+1;j<l;j++) { if(str[i].compareTo(str[j])>0) { String t=str[j]; str[j]=str[i]; str[i]=t; } } } for(int i=0;i<l;i++) { System.out.println(str[i]); } } }

7|Page

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

Program 6 Write a Java program to implement the matrix ADT using a class. The operations supported by this ADT are: (b) Reading a Matrix (d) Subtraction of Matrix (b) Printing a Matrix (c) Addition of Matrix (e) Multiplication of Matrix

8|Page

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 7

M. Tech(IT)

Write a Java program that uses a recursive function to compute ncr. ( Note: n and r values are given).

9|Page

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 8 Write a java program to make frequency count of words in a given text

M. Tech(IT)

10 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 9

M. Tech(IT)

Write a Java program that reads a 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. //Print file status import java.io.*; class readfile { public static void main(String []args) throws IOException { DataInputStream d1= new DataInputStream(System.in); System.out.println("enter the file name"); String text=d1.readLine(); File f1=new File(text); if(f1.exists()) { System.out.println("name of the parent"+f1.getParent()); System.out.println("complete pathfile"+f1.getPath()); if(f1.canRead()) { System.out.println("it can read"+" "+"yes"); } else { System.out.println("it can read"+"no"); } if(f1.canWrite()) { System.out.println("it can write"+"yes"); } else { System.out.println("it can't write"+"no"); } System.out.println("length of the file"+f1.length()); if(f1.isDirectory()) { System.out.println("it is a Directory"+"yes"); } else { System.out.println("it is not a directory"+"no"); } if(f1.isFile()) 11 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual { System.out.println("it is a file"+"yes"); } else { System.out.println("file does not exist"); } } } }

M. Tech(IT)

12 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

Program 10 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 file2 { public static void main(String argv[])throws IOException { DataInputStream d = new DataInputStream(System.in); System.out.println("Enter File Name"); String fname = d.readLine(); FileInputStream fi = new FileInputStream(fname); int i=0;int n=1; System.out.println(n+"."); while((i=fi.read())!= -1) { System.out.print((char)i); if(i == '\n') { n++; System.out.print("\n"+n+"."); } } fi.close(); } }

13 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 11 Write a Java program that implements the Stack ADT import java.io.*; class Underflow extends Exception { public String toString() { return "Stack Underflow"; } } class Overflow extends Exception { public String toString() { return "Stack Overflow"; } } class St { final int max=10; int[] a=new int[max]; int top=-1; void push(int p) throws Overflow { if(top==max-1) { throw new Overflow(); } top++; a[top]=p; } int pop() throws Underflow { if(top==-1) { throw new Underflow(); } int p=a[top]; top--; 14 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual return(p); } void disp() throws Underflow { if(top==-1) { throw new Underflow(); } for(int i=0;i<=top;i++) { System.out.println(a[i]); } } public static void main(String args[]) throws IOException {

M. Tech(IT)

InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); St s = new St(); int ch; String flag="y"; while(flag.equals("y")) { System.out.println("Menu Driven programme"); System.out.println("1.Insert an element"); System.out.println("2.Delete an element"); System.out.println("3.Display an list"); System.out.println("4.exit"); System.out.println("Enter U R choice"); ch=Integer.parseInt(br.readLine()); System.out.println("Menu Driven programme"+ch); switch(ch) { case 1: try { System.out.println("Enter an element to insert:"); int ele=Integer.parseInt(br.readLine()); s.push(ele); break; } catch(Overflow e) { System.out.println(e); 15 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual } case 2:

M. Tech(IT)

try { int temp=s.pop(); System.out.println("Deleted element is"+ temp); break; } catch(Underflow e) { System.out.println(e); } case 3: try { s.disp(); break; } catch(Underflow e) { System.out.println(e); } default: return; } System.out.println("Do u want to continue"); flag=br.readLine(); } } }

16 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 12

M. Tech(IT)

Develop an applet in java that receives an integer in one text filed and computes its factorial value and returns it in another text field. When the button named Compute is clicked.

17 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 13

M. Tech(IT)

Write a Java program that works as a simple calculator. Use the Grid layout to arrange buttons for this digits and for the +,-,*,/,% operations. Add a text filed to display the result.

18 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 14 Write a java program for handling mouse events.

M. Tech(IT)

//Handling Mouse Events import java.awt.*; import java.awt.event.*; import java.applet.*; import java.awt.event.MouseEvent; /*<applet code=MouseEvents width=100 height=100> </applet>*/ public class MouseEvents extends Applet implements MouseListener,MouseMotionListener { String str; int x=0,y=0; public void init() { setBackground(Color.red); setForeground(Color.blue); addMouseListener(this); addMouseMotionListener(this); } public void mouseExited(MouseEvent me) { str="mouse exited"; x=10;y=40; repaint(); } public void mouseClicked(MouseEvent me) { str="MouseClicked action occured"; x=me.getX(); y=me.getY(); repaint(); } public void mouseEntered(MouseEvent me) { str="Mouse Entered"; x=10; y=20; repaint(); } public void mousePressed(MouseEvent me) { str="Mouse Pressed"; 19 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual x=10; y=10; repaint(); } public void mouseReleased(MouseEvent me) { str="Mouse Released"; x=me.getX(); y=me.getY(); y=10; repaint(); } public void mouseMoved(MouseEvent me) { str="Mouse moved"; showStatus(str+"at"+me.getX()+me.getY()); } public void mouseDragged(MouseEvent me) { showStatus("mouse dragged at"+me.getX()+me.getY()); } public void paint(Graphics g) { g.drawString(str,x,y); } }

M. Tech(IT)

20 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 15

M. Tech(IT)

Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication.

//Producer Consumer problem class Q { int n; boolean valueset=false; synchronized int get() { if(!valueset) try { wait(); } catch(InterruptedException e) { System.out.println(e); } System.out.println("get:"+n); valueset=false; notify(); return n; } synchronized void put(int n) { if(valueset) try { wait(); } catch(InterruptedException e) { System.out.println(e); } this.n=n; valueset=true; System.out.println("put:"+n); notify(); } } class producer implements Runnable { 21 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Q q; Thread t1; producer(Q q) { this.q=q; t1=new Thread(this,"producer"); t1.start(); } public void run() { int i=0; while(true) { q.put(i++); //Thread.sleep(200); } } } class consumer implements Runnable { Q q; Thread t; consumer(Q q) { this.q=q; t=new Thread(this,"consumer"); t.start(); } public void run() { while(true) { q.get(); //Thread.sleep(200); } } } class pc { public static void main(String args[]) { Q q=new Q(); new producer(q); new consumer(q); System.out.println("press control c to stop"); 22 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual } }

M. Tech(IT)

23 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 16

M. Tech(IT)

Write a java program that creates user interface to perform integer division. The user enters two numbers in the text fields Num1 and Num2. The division of two numbers is displayed in the result field when the divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a Number format exception. If Num2 were Zero, the program would throw an Arithmetic Exception display the exception in a message dialog box.

24 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

Program 17 Write a java program that illustrates the following a) Creation of simple package. b) Accessing a package. c) Implementing interfaces. Creation of Package package MyPack; class Balance { String name; double bal; Balance(String n, double b) { name = n; bal = b; } void show() { if(bal<0) System.out.print("--> "); System.out.println(name + ": $" + bal); } } Accessing Package import p1.*; class AccountBalance { public static void main(String args[]) { Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell", 157.02); current[2] = new Balance("Tom Jackson", -12.33); for(int i=0; i<3; i++) current[i].show(); } }

25 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Implementing Interface // declaration of interface public interface Intf1 { void disp1(); void disp2(); int a=10; } // implementing interface class Impl implements intf1 { public void disp1() { System.out.println(" I am in display1"); } public void disp2() { System.out.println(" I am in display2"); } } class Int1 { public static void main(String args[]) { Impl i = new Impl(); i.disp1(); i.disp2(); System.out.println(i.a); } }

M. Tech(IT)

26 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 18 Write a java program that illustrates the following a) Handling predefined exceptions b) Handling user defined exceptions Class trycatch { Public static void main(String args[]) { Int[] no={1,2,3}; Try { System.out.println(no[3]); } Catch(ArrayIndexOutOfBoundsException e) { System.out.println(Out of bonds); } System.out.println(Quit); } } Class ArithExce { Public static void main(String args[]) { Int a=10; Int b=0; Try { a=a/b; System.out.println(Wont Print); } Catch(ArithmeticException e) { System.out.println(Division by Zero error); System.out.println(Change the b value); } System.out.println(Quit); } }

M. Tech(IT)

27 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual User defined exception Class ownExcepion extends Exception { ownException(String msg) { Super(msg); } } Class test { Public static void main(String args[]) Int mark=101; Try { if(mark>100) { Throw new ownException(Marks>100); } } Catch(ownException e) { System.out.println (Exception caughtr); System.out.println.(e.getMessage()); } Finally { System.out.println(End of prg); } } }

M. Tech(IT)

28 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 19

M. Tech(IT)

Write Java programs that use both recursive and non-recursive functions for implementing the following searching methods: a) Linear search b) Binary search class LinearSearchDemo { static Object[] a = { 89, 45, 175, 7, 50, 43, 126, 90 }; static Object key = 126; public static void main(String args[]) { if( linearSearch() ) System.out.println(key + " found in the list"); else System.out.println(key + " not found in the list"); } static boolean linearSearch() { for( int i=0; i<a.length; i++) if(key == a[i]) return true; return false; } } Recursive Linear search class RecursiveLinearSearchDemo { static Object[] a = { 89, 45, 175, 7, 50, 43, 126, 90 }; static Object key = 43; public static void main(String args[]) { if( linearSearch(a.length-1) ) System.out.println(key + " found in the list"); else System.out.println(key + " not found in the list"); } static boolean linearSearch(int n) { if( n < 0 ) return false; if(key == a[n]) return true; else return linearSearch(n-1); } } 29 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

Binary Search

import java.io.*; public class BinarySearch { public static final int NOT_FOUND = -1; public static int binarySearch( Comparable [ ] a, Comparable x ) { int low = 0; int high = a.length - 1; int mid; while( low <= high ) { mid = ( low + high ) / 2; if( a[ mid ].compareTo( x ) < 0 ) low = mid + 1; else if( a[ mid ].compareTo( x ) > 0 ) high = mid - 1; else return mid; } return NOT_FOUND; // NOT_FOUND = -1

} public static void main( String [ ] args ) throws IOException { int SIZE = 4; Comparable [ ] a = new Integer [ SIZE ]; DataInputStream dr=new DataInputStream(System.in); System.out.println("enter the elements"); for( int i = 0; i < SIZE; i++ ) a[ i ] =(char)dr.read(); for( int i = 0; i < SIZE * 2; i++ ) System.out.println( "Found " + i + " at " + binarySearch( a, new Integer( i ) ) ); } } 30 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

31 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 20 Write Java programs to implement the Queue ADT using an array. Queue ADT class Qu { char[] o = new char[10]; int front=-1,rear=-1; void insert(char ele) { if(rear==9) { System.out.println("Queue is full"); return; } rear++; o[rear]=ele; if(front==-1) front++; } char del() { if(front==-1) { System.out.println("Queue is empty"); return('0'); } char op = o[front]; front++; return(op); } void disp() { for(int i=front;i<=rear;i++) { System.out.println(o[i]); } } 32 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

public static void main(String args[]) { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); Qu q =new Qu(); int ch; String flag="y"; while(flag.equals("y")) { System.out.println("Menu Driven programme"); System.out.println("1.Insert an element"); System.out.println("2.Delete an element"); System.out.println("3.Display an list"); System.out.println("4.exit"); System.out.println("Enter U R choice"); ch=Integer.parseInt(br.readLine()); System.out.println("Menu Driven programme"+ch); switch(ch) { case 1: System.out.println("Enter an element to insert:"); char ele=br.readLine().charAt(0); q.push(ele); break; case 2: char temp=q.pop(); System.out.println("Deleted element is"+ temp); break; case 3: q.disp(); break; default: return; } System.out.println("Do u want to continue"); flag=br.readLine(); } } }

33 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 21 Write Java programs to implement the following using a singly linked list. a) Stack ADT b) Queue ADT 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 } class LinkedStack { 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; 34 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual } 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 35 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual { return (top == null); } } ///////////////////////// LinkedStackDemo.java ///////////////// class LinkedStackDemo { 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 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 ) 36 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual { System.out.println(Popped item: + item.data); stk.displayStack(); } System.out.println(peek(): + stk.peek());// get top item 4. Stacks and Queues 45 stk.push(90); // insert 90 stk.displayStack(); } Output from LinkedStack operations program: 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 peek(): 70 Contents of Stack: [ 70 65 35 20 ] Contents of Stack: [ 90 70 65 35 20 ]

M. Tech(IT)

A LinkedQueue Class public class LinkedQueue { class Node { Object data; 37 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Node next; Node(Object item) // constructor { 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; } Lab Manual Data Structures through Java 46 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; } 38 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual 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; } 39 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual System.out.println(); } } class LinkedQueueDemo { 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()); } }

M. Tech(IT)

40 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 22 Write Java programs to implement the deque (double ended queue) ADT using a) Array b) Singly linked list c) Doubly linked list. import java.io.*; class Deque { Object arr[]; int front,rear,count; final int size = 5; Deque(){ front = -1; rear = -1; count = 0; arr = new Object[size]; } void insertFirst(Object elt) { if(front == -1) front = 0; for(int i=rear;i>=front;i--) arr[i+1] = arr[i]; arr[front] = elt; rear++; count++; } void insertLast(Object elt) { arr[++rear] = elt; count++; } Object removeFirst() { count--; return arr[front++]; } 41 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

Object removeLast() { count--; return arr[rear--]; } Object first() { return arr[front]; } Object last() { return arr[rear]; } int sizeQ() { return count; } boolean isFull() { return rear == size -1; } boolean isEmpty() { return front > rear || front == -1; } void disp() { System.out.println("The elements are:"); for(int i = front;i<=rear;i++) System.out.print(arr[i]+" "); System.out.println(); } } class prg22{ public static void main(String args[]) throws IOException { 42 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Object elt; Deque dq = new Deque();//object of Deque int choice; while(true) { System.out.println("**********************************"); System.out.println(" DEQUEUE MENU "); System.out.println("**********************************"); System.out.println(" 1.insertFirst\n 2.insertLast\n 3.removeFirst\n 4.removeLast\n 5.first\n 6.last\n 7.size\n 8.display\n 9.exit"); System.out.println("**********************************"); System.out.println("Enter your choice:"); choice = Integer.parseInt(br.readLine()); switch(choice) { case 1: if(dq.isFull()) System.out.println("Deque full"); else { System.out.println("Enter an element:"); elt = br.readLine(); dq.insertFirst(elt); } break; case 2: if(dq.isFull()) System.out.println("Deque full"); else { System.out.println("Enter an element:"); elt = br.readLine(); dq.insertLast(elt); } break; case 3: if(dq.isEmpty()) System.out.println("Deque is empty"); else System.out.println("The deleted element is:"+dq.removeFirst()); break; case 4: if(dq.isEmpty()) 43 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual System.out.println("Deque is empty"); else System.out.println("The deleted element is:"+dq.removeLast()); break; case 5: if(dq.isEmpty()) System.out.println("Deque is empty"); else System.out.println("The first element is:"+dq.first()); break; case 6: if(dq.isEmpty()) System.out.println("Deque is empty"); else System.out.println("The last element is:"+dq.last()); break; case 7: if(dq.isEmpty()) System.out.println("Deque is empty"); else System.out.println("The number of elements is:"+dq.sizeQ()); break; case 8: if(dq.isEmpty()) System.out.println("Deque is empty"); else dq.disp(); break; case 9: default: System.exit(0); } } } }

M. Tech(IT)

44 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 23 Write a java program to implement priority queue ADT.

M. Tech(IT)

45 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 24 Write a java program to implement priority queue ADT.

M. Tech(IT)

46 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 25 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.

M. Tech(IT)

47 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 26

M. Tech(IT)

Write a Java program to implement all the functions of a dictionary (ADT) using Hashing.

48 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 27 Write a Java program to implement circular queue ADT using an array. import java.io.*; class Queue { Object arr[]; final int size = 5; int front,rear; Queue() { arr = new Object[size]; front = -1; rear = -1; } void insert(Object el) { if(front == -1) front = 0; if(rear == size -1) rear = 0; rear = (rear + 1)%size; arr[rear] = el; } Object del() { return arr[front++]; } boolean isFull() { if(rear ==size-1) return true; else return false; } boolean isEmpty() { return front > rear ; } void dispQueue() { 49 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual System.out.println("The elements int the queue are:"); for(int i = front;i<=rear;i++) System.out.println(arr[i]); } }

M. Tech(IT)

class prg26 { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Queue qu = new Queue(); Object el; int choice; while(true) { System.out.println("\n1.insert\n2.delete\n3.dispQueue\n4.exit:"); choice = Integer.parseInt(br.readLine()); switch(choice) { case 1: if(qu.isFull()) { System.out.println("The queue is full"); } else { System.out.println("Enter an element to insert into the queue:"); el = br.readLine(); qu.insert(el); } break; case 2: if(qu.isEmpty()) System.out.println("Queue is empty"); else { System.out.println("The deleted element is : "+qu.del()); } break; case 3: if(qu.isEmpty()) System.out.println("Queue is empty there is nothing to display"); else qu.dispQueue(); break; case 4: 50 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual System.out.println("Exiting the Queue program"); System.exit(0); } } } }

M. Tech(IT)

51 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 28 Write Java programs that use recursive and non-recursive functions to traverse the given binary tree in a) Preorder b) Inorder and c) Postorder.

M. Tech(IT)

52 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 29 Write Java programs for the implementation of bfs and dfs for a given graph.

M. Tech(IT)

53 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 30 Write Java programs for implementing the following sorting methods: a) Bubble sort d) Quick sort g) Radix sort b) Selection sort e) Merge sort h) Binary tree sort c) Insertion sort f) Heap sort Bubble sort import java.lang.*; import java.io.*; class Bsort { public static void main(String as[]) throws IOException { int n,i,j,temp; DataInputStream su=new DataInputStream(System.in); System.out.println("Enter size"); n=Integer.parseInt(su.readLine()); int a[]=new int[n]; System.out.println("Enter elements to be sorted"); for(i=0;i<n;i++) { a[i]=Integer.parseInt(su.readLine()); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if (a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } System.out.println("Sorted elements are"); for(i=0;i<n;i++) System.out.println(" "+a[i]); } }

M. Tech(IT)

54 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Insertion sort import java.lang.*; import java.io.*; class Isort { public static void main(String ar[]) throws IOException { int n,i,j,temp; DataInputStream ds=new DataInputStream(System.in); System.out.println("Enter size"); n=Integer.parseInt(ds.readLine()); int a[]=new int[n]; System.out.println("Enter elements to be sorted"); for(i=0;i<n;i++) { a[i]=Integer.parseInt(ds.readLine()); } for(i=0;i<n;i++) { for(j=0;j<i;j++) { if(a[i]<a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } System.out.println("Sorted elements are"); for(i=0;i<n;i++) System.out.println(" "+a[i]); } }

M. Tech(IT)

55 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Selection sort import java.lang.*; import java.io.*; class Ssort { public static void main(String as[]) throws IOException { int n,i,pos=-1,min,j; DataInputStream su=new DataInputStream(System.in); System.out.println("Enter size"); n=Integer.parseInt(su.readLine()); int a[]=new int[n]; System.out.println("Enter elements to be sorted"); for(i=0;i<n;i++) { a[i]=Integer.parseInt(su.readLine()); } for(i=0;i<n;i++) { min=a[i]; pos=i; for(j=i+1;j<n;j++) { if(min>a[j]) { min=a[j]; pos=j; } } a[pos]=a[i]; a[i]=min; } System.out.println("Sorted elements are"); for(i=0;i<n;i++) System.out.println(" "+a[i]); } }

M. Tech(IT)

56 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

Merge sort class Mergesort { int[] a ={100,171,151,119,112,118,132}; Mergesort() { System.out.println("Elements before sort:"); disp(); System.out.println("Elements after sort:"); mergesort(0,a.length-1); disp(); }

void mergesort(int low,int high) { if(low<high) { int mid=(low+high)/2; mergesort(low,mid); mergesort(mid+1,high); merge(low,mid,high); } } void merge(int low,int mid,int high) { int h,i,j,k; int[] b = new int[a.length]; h=low; i=low; j=mid+1; while((h<=mid)&&(j<=high)) { if(a[h]<=a[j]) { b[i]=a[h]; h++; } else { b[i]=a[j]; j++; 57 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual } i++; } if(h>mid) { for(k=j;k<=high;k++) { b[i]=a[k]; i++; } } else { for(k=h;k<=mid;k++) { b[i]=a[k]; i++; } } for(k=low;k<=high;k++) { a[k]=b[k]; } } void disp() { for(int i=0;i<a.length;i++) System.out.println(a[i]); } public static void main(String args[]) { new Mergesort(); } }

M. Tech(IT)

58 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual class Heapsort { int[] a ={100,171,151,119,112,118,132}; Heapsort() { System.out.println("Elements before sort:"); disp(); System.out.println("Elements after sort:"); heapsort(a.length-1); disp(); } void heapsort(int n) { heapify(n); for(int i=n;i>0;i--) { int t=a[i]; a[i]=a[0]; a[0]=t; adjust(0,i-1); } } void heapify(int n) { for(int i=n/2;i>=0;i--) adjust(i,n); } void adjust(int i,int n) { int j=2*i; int temp=a[i]; while(j<=n) { if((j<n)&&(a[j]<a[j+1])) j++; if(temp>=a[j]) break; a[j/2]=a[j]; j=2*j; } a[j/2]=temp; } 59 | P a g e

M. Tech(IT)

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual

M. Tech(IT)

void disp() { for(int i=0;i<a.length;i++) System.out.println(a[i]); } public static void main(String args[]) { new Heapsort(); } }

60 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual class Quicksort { int[] a ={100,171,151,119,112,118,132}; Quicksort() { System.out.println("Elements before sort:"); disp(); System.out.println("Elements after sort:"); qsort(0,a.length-1); disp(); }

M. Tech(IT)

void qsort(int p,int q) { int i,j; int key,temp; if(p<q) { i=1; j=q; key=a[p]; while(i<=j) { while((key<=a[i])&&(i<=q)) i++; while((key>=a[j])&&(j>p)) j--; if(i<j) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } temp=a[p]; a[p]=a[j]; a[j]=temp; qsort(p,j-1); qsort(j+1,q); } } void disp() { for(int i=0;i<a.length;i++) 61 | P a g e Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual System.out.println(a[i]); } public static void main(String args[]) { new Quicksort(); } }

M. Tech(IT)

62 | P a g e

Institute of Aeronautical Engineering

Advanced Problem Solving Lab Manual Program 31 Write a java program that uses recursive functions a. To create a binary search tree. b. To count the number of leaf nodes. c. To copy the above binary search tree.

M. Tech(IT)

63 | P a g e

Institute of Aeronautical Engineering