Académique Documents
Professionnel Documents
Culture Documents
} Output: Enter a,b,c values of the Quadratic eqn 2 3 1 The roots are real And the roots are -0.5 -1.0
System.out.println("Enter any no to print all prime nos upto it"); int m=Integer.parseInt(br.readLine()); int j,count; System.out.println("\nThe prime nos upto "+m+" are:\n"); for(int i=2;i<=m;i++) { j=1; count=0; while(j<=i/2) { if(i%j++==0) count++; } if(count==1) System.out.print(i+" "); } } } Output: Enter any no to print all prime nos upto it 25 The prime nos upto 25 are: 2 3 5 7 11 13 17 19 23
public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the no of names"); int n=Integer.parseInt(br.readLine()); String str[]=new String[n]; System.out.println("Enter the names"); for(int i=0;i<n;i++) str[i]=br.readLine(); String temp; for(int i=0;i<n;i++) for(int j=0;j<n-i-1;j++) if(str[j].compareTo(str[j+1])>0) { temp=str[j]; str[j]=str[j+1]; str[j+1]=temp; } System.out.println("\n\nAfter sorting the names are:"); for(int i=0;i<n;i++) System.out.println(str[i]); } } Output: Enter the no of names 4 Enter the names charan arjun chandra anil After sorting the names are: anil arjun chandra charan
mat[i][j]=Integer.parseInt(br.readLine()); } void display() { for(int i=0;i<r;i++) { for(int j=0;j<c;j++) System.out.print("\t"+mat[i][j]); System.out.println("\n"); } } void multiply(Matrix m1,Matrix m2) { for(int i=0;i<m1.r;i++) for(int j=0;j<m2.c;j++) { mat[i][j]=0; for(int k=0;k<m1.c;k++) mat[i][j]=mat[i][j]+m1.mat[i][k]*m2.mat[k][j]; } } } class Matmul { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Matrix m[]=new Matrix[3]; System.out.println("Enter the order of first matrix"); int m1=Integer.parseInt(br.readLine()); int n1=Integer.parseInt(br.readLine()); m[0]=new Matrix(m1,n1); m[0].getData(br); System.out.println("Enter the order of second matrix"); int m2=Integer.parseInt(br.readLine()); int n2=Integer.parseInt(br.readLine()); if(n1==m2) { m[1]=new Matrix(m2,n2); m[1].getData(br); m[2]=new Matrix(m1,n2); m[2].multiply(m[0],m[1]); System.out.println("First matrix is:\n"); m[0].display(); System.out.println("Second matrix is:\n"); m[1].display(); System.out.println("Product matrix is:\n"); m[2].display(); } else System.out.println("Multiplication is not possible"); } } Output:
Enter the order of first matrix 2 2 Enter the elements 1 2 3 4 Enter the order of second matrix 2 2 Enter the elements 5 1 3 4 First matrix is: 1 3 2 4
} catch(NumberFormatException nfe) { System.out.println("\n NumberFormatException"); } } } Output: Enter the integers seperated by commas or spaces 1235467 The given integers are: 1 2 3 5 4 6 7 Sum of all the integers is: 28
import java.io.*; class File2 { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the File name"); String str=br.readLine(); try { FileInputStream fis=new FileInputStream(str); System.out.println("\nThe contents of "+str+" line by line:"); int c,d=0,i=1; System.out.print("Line "+i+": "); while((c=fis.read())!=-1) { System.out.print((char)c); if(c==13) d=c; if(d==13&&c==10) System.out.print("Line "+(++i)+": "); } fis.close(); } catch(FileNotFoundException e) { System.out.println("File not found"); } catch(IOException e) { System.out.println("File read error"); } } } Output: Enter the File name hello.java The contents of hello.java line by line: Line 1: class Hello Line 2: { Line 3: public static void main(String[] args) Line 4: { Line 5: System.out.println("Hello World!"); Line 6: } Line 7: } Line 8:
/*Program 10: Count number of chars, lines and words in a text file*/
import java.io.*; class File3 { public static void main(String ar[]) throws IOException
{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the File name"); String str=br.readLine(); try { FileInputStream fis=new FileInputStream(str); int c,d=0,lc=0,wc=0,cc=0; System.out.println(); System.out.println("The contents of "+str+" are:"); while((c=fis.read())!=-1) { System.out.print((char)c); if(c==13) d=c; else if(d==13&&c==10) { lc++; wc++; } else if(c==32) { wc++; cc++; } else cc++; } System.out.println("\nNo of characters="+cc+"\nNo of words ="+(++wc)+"\nNo of lines ="+(++lc)); fis.close(); } catch(FileNotFoundException e) { System.out.println("File not found"); } catch(IOException e) { System.out.println("File read error"); } } } Output: Enter the File name hello.java The contents of hello.java are: class Hello { public static void main(String[] args) { System.out.println("Hello World!"); } }
10
Thread th; AThread( String threadName) { name = threadName; th = new Thread(this, name); System.out.println("A Thread: " + th); th.start(); } public void run() // entry point for the thread { try { for(int k = 3; k > 0; k--) { System.out.println(name + ":" + k); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println(name + "Interrupted"); } System.out.println(name + " exiting"); } } class MultiThreadDemo { public static void main(String[] args) { new AThread("One"); // start threads new AThread("Two"); new AThread("Three"); try { Thread.sleep(10000); // wait for others to end } catch(InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting"); } } Output: A Thread: Thread[One,5,main] A Thread: Thread[Two,5,main] A Thread: Thread[Three,5,main] One:3 Two:3 Three:3 One:2 Two:2 Three:2 One:1 Two:1 Three:1 One exiting Two exiting Three exiting Main thread exiting
11
} } class B extends A{ void display() { System.out.println("\nInside the method display of B"); } } class C extends A{ void display() { System.out.println("\nInside the method display of C"); } } class RTPoly{ public static void main(String ar[]) { A ref; ref=new A(); ref.display(); ref=new B(); ref.display(); ref=new C(); ref.display(); } } output for 12: Inside the method display of A Inside the method display of B Inside the method display of C
12
obj.display(); } } Output: In show method of XYZ class of mypack package Interface ABC is implemented by XYZ in mypack package
13
AE not encountered caught AIOOBE From finally block //14b. User defined exceptions import java.io.*; class InvalidMarksException extends Exception { int num; InvalidMarksException(int n) { num=n; } public String toString() { return("\nNumber entered is "+num+",and is invalid"); } } class CheckNumber { public void checkNum(int n) throws InvalidMarksException { int k; if(n<0||n>100) { throw new InvalidMarksException(n); } }} class UserExcDemo { public static void main(String ar[]) { CheckNumber cn=new CheckNumber(); try { cn.checkNum(Integer.parseInt(ar[0])); } catch(InvalidMarksException ime) { System.out.println("Caught InvalidMarksException"+ime.toString()); } }} Output: C:\DS>java UserExcDemo 2 C:\DS>java UserExcDemo -1 Caught InvalidMarksException Number entered is -1,and is invalid C:\DS>java UserExcDemo 101 Caught InvalidMarksException Number entered is 101,and is invalid C:\DS>java UserExcDemo 10
14
/* Program 15: programs 4 linear search and binary search using recursive and non-recursive functoins */
//Program 15.a import java.io.*; class NonreclinSearchDemo { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the no of elements"); int size=Integer.parseInt(br.readLine()); int[] a=new int[size]; System.out.println("Enter the elements"); for(int i=0;i<size;i++) a[i]=Integer.parseInt(br.readLine()); System.out.println("\n\nEnter the element to be searched"); int key=Integer.parseInt(br.readLine()); System.out.println("Searching the element using nonrecursive linear search....."); br.readLine(); int flag=0; for(int i=0;i<size;i++) if(a[i]==key) { System.out.println("Element "+key+" is found at location "+(++i)); flag=1; } if(flag==0) System.out.println("Element "+key+" is not found"); } } Output: E:\CHANDU\SYL>java NonreclinSearchDemo Enter the no of elements 6 Enter the elements 4 6 2 8 5 1 Enter the element to be searched 10 Searching the element using nonrecursive linear search..... Element 10 is not found //Program 15.b import java.io.*; class ReclinSearchDemo { static void reclin(int a[],int key,int size) { if(a[--size]==key)
15
System.out.println("Element "+key+" is found at location "+(size+1)); else if(size>0) reclin(a,key,size); else System.out.println("Element "+key+" is not found"); } public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the no of elements"); int size=Integer.parseInt(br.readLine()); int[] a=new int[size]; System.out.println("Enter the elements"); for(int i=0;i<size;i++) a[i]=Integer.parseInt(br.readLine()); System.out.println("\n\nEnter the element to be searched"); int key=Integer.parseInt(br.readLine()); System.out.println("Searching the element using Recursive linear search....."); br.readLine(); reclin(a,key,size); } } Output: E:\CHANDU\SYL>java ReclinSearchDemo Enter the no of elements 5 Enter the elements 1 89 6 4 2 Enter the element to be searched 6 Searching the element using nonrecursive linear search..... Element 6 is found at location 3 //Program 15.c import java.io.*; class NonrecbinSearchDemo { int a[],max; NonrecbinSearchDemo(int size) { max=size; a=new int[max]; } void sort() { for(int i=0;i<max;i++) for(int j=0;j<max-i-1;j++) if(a[j]>a[j+1]) {
16
int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } System.out.println("After sorting the array is:"); for(int i=0;i<max;i++) System.out.print(a[i]+" "); } void nonrecbin(int key) { int l=0,h=max-1,mid; boolean flag=false; sort(); while(l<=h) { mid=(l+h)/2; if(a[mid]==key) { System.out.println("\nElement is found at location "+(++mid)); flag=true; break; } else if(a[mid]<key) l=mid+1; else if(a[mid]>key) h=mid-1; } if(!flag) System.out.println("\nElement is not found"); } public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the no of elements"); int size=Integer.parseInt(br.readLine()); int[] a=new int[size]; NonrecbinSearchDemo nrbs=new NonrecbinSearchDemo(size); System.out.println("Enter the elements"); for(int i=0;i<size;i++) nrbs.a[i]=Integer.parseInt(br.readLine()); System.out.println("\n\nEnter the element to be searched"); int key=Integer.parseInt(br.readLine()); System.out.println("Searching the element using nonrecursive linear search....."); br.readLine(); nrbs.nonrecbin(key); } } //Program 15.d import java.io.*; class RecbinSearchDemo { static void sort(int a[],int max) { for(int i=0;i<max;i++)
17
for(int j=0;j<max-i-1;j++) if(a[j]>a[j+1]) { int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } System.out.println("After sorting the array is:"); for(int i=0;i<max;i++) System.out.print(a[i]+" "); } static void recbin(int a[],int key,int l,int h) { int mid; boolean flag=false; if(l<=h) { mid=(l+h)/2; if(a[mid]==key) { System.out.println("\nElement is found at location "+(++mid)); flag=true; } else if(a[mid]<key) recbin(a,key,mid+1,h); else if(a[mid]>key) recbin(a,key,l,mid-1); } else if(!flag) System.out.println("\nElement is not found"); } public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the no of elements"); int size=Integer.parseInt(br.readLine()); int[] a=new int[size]; System.out.println("Enter the elements"); for(int i=0;i<size;i++) a[i]=Integer.parseInt(br.readLine()); System.out.println("\n\nEnter the element to be searched"); int key=Integer.parseInt(br.readLine()); System.out.println("Searching the element using recursive binary search....."); br.readLine(); sort(a,size); recbin(a,key,0,size-1); } } Output: E:\CHANDU\SYL>java RecbinSearchDemo Enter the no of elements 6 Enter the elements 4
18
6 2 8 5 1 Enter the element to be searched 10 Searching the element using recursive binary search..... After sorting the array is: 1 2 4 5 6 8 Element is not found
19
return false; } public int search(int key) { for(int i=0;i<n;i++) if(a[i]==key) return i; return -1; } public void insertAtBeg(int item) { if(!isFull()) { for(int i=n-1;i>=0;i--) a[i+1]=a[i]; a[0]=item; n++; } else System.out.println("Array is Full, cannot insert"); } public void insertAtEnd(int item) { if(!isFull()) { a[n++]=item; } else System.out.println("Array is Full, cannot insert"); } public void insertAtPos(int pos,int item) { if(!isFull()) { for(int i=n-1;i>=pos;i--) a[i+1]=a[i]; a[pos]=item; n++; } else System.out.println("Cannot insert, Array is Full"); } public void insertAfterPos(int pos,int item) { if(pos<n) insertAtPos(pos+1,item); else System.out.println("Array is Full, cannot insert"); } public void insertAfterKey(int key,int item) { int p=search(key); if(p==-1) System.out.println("Cannot insert"); else
20
insertAfterPos(p,item); } public void delete(int key) { if(!isEmpty()) { int p=search(key); deletePos(p); } else System.out.println("Array is Empty"); } public void deletePos(int pos) { if(!isEmpty()) { if(pos<0||pos>n-1) { System.out.println("Cannot delete, Element not found"); } else { for(int i=pos;i<n-1;i++) a[i]=a[i+1]; n--; } } else System.out.println("Array is Empty"); } } class ArrayTest { public static void main(String arg[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the size of the Array"); int n=Integer.parseInt(br.readLine()); ArrayDS ar=new ArrayDS(n); System.out.println("Array is created"); ar.traversal(); int t,k,m=1; do { System.out.println("Enter ur choice of operation"); System.out.println("1-insertAtBeg\n2-insertAtEnd\n3-insertAtPos\n4-insertAfterPos\n5insertAfterKey\n6-deleteItem\n7-deletePos\n0-exit"); n=Integer.parseInt(br.readLine()); switch(n) { case 1: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); ar.insertAtBeg(t); ar.traversal();
21
break; case 2: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); ar.insertAtEnd(t); ar.traversal(); break; case 3: System.out.println("Enter the element to be inserted:"); t=Integer.parseInt(br.readLine()); System.out.println("Enter the index position to insert at:"); k=Integer.parseInt(br.readLine()); ar.insertAtPos(k,t); ar.traversal(); break; case 4: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); System.out.println("Enter the index position to insert after"); k=Integer.parseInt(br.readLine()); ar.insertAfterPos(k,t); ar.traversal(); break; case 5: System.out.println("Enter the element to be inserted:"); t=Integer.parseInt(br.readLine()); System.out.println("Enter the key element to insert aftter:"); k=Integer.parseInt(br.readLine()); ar.insertAfterKey(k,t); ar.traversal(); break; case 6: System.out.println("Enter the element to be deleted"); t=Integer.parseInt(br.readLine()); ar.delete(t); ar.traversal(); break; case 7: System.out.println("Enter the position to be deleted"); t=Integer.parseInt(br.readLine()); ar.deletePos(t); ar.traversal(); break; case 0: m=0; break; default: System.out.println("INVALID CHOICE"); } }while(m==1); ar.traversal(); } } Output:
22
Enter the size of the Array 5 Array is created Enter ur choice of operation 1-insertAtBeg 2-insertAtEnd 3-insertAtPos 4-insertAfterPos 5-insertAfterKey 6-deleteItem 7-deletePos 0-exit 1 Enter the element to be inserted 10 10 Enter ur choice of operation 1-insertAtBeg 2-insertAtEnd 3-insertAtPos 4-insertAfterPos 5-insertAfterKey 6-deleteItem 7-deletePos 0-exit 2 Enter the element to be inserted 40 10 40 Enter ur choice of operation 1-insertAtBeg 2-insertAtEnd 3-insertAtPos 4-insertAfterPos 5-insertAfterKey 6-deleteItem 7-deletePos 0-exit 3 Enter the element to be inserted: 20 Enter the index position to insert at: 2 10 40 20 Enter ur choice of operation 1-insertAtBeg 2-insertAtEnd 3-insertAtPos 4-insertAfterPos 5-insertAfterKey
23
6-deleteItem 7-deletePos 0-exit 6 Enter the element to be deleted 40 10 20 Enter ur choice of operation 1-insertAtBeg 2-insertAtEnd 3-insertAtPos 4-insertAfterPos 5-insertAfterKey 6-deleteItem 7-deletePos 0-exit 0 10 20
24
this.data=data; this.next=next; } } class LLoperation implements ListADT { Node First,Last,ptr; public void createLL(int num) { Node nn; for(int i=0;i<num;i++) { nn=new Node(i*10); if(First==null) { First=Last=nn; } else { Last.next=nn; Last=nn; } } } public void traversal() { Node ptr; ptr=First; while(ptr!=null) { System.out.print(ptr.data); ptr=ptr.next; if(ptr!=null) System.out.print(" -> "); } System.out.println(); } public Node search(int key) { Node ptr=First; while(ptr!=null) { if(ptr.data==key) return ptr; ptr=ptr.next; } return ptr; } public boolean isFirst(Node n) { Node n1=getPrevNode(n); if(n1==null) return true; else return false;
25
} public Node getPrevNode(Node n) { if(n==First) return null; ptr=First; while(ptr!=null) { if(ptr.next==n) return ptr; ptr=ptr.next; } return ptr; } public Node getNextNode(Node n) { return n.next; } public void insertAtBeg(int item) { Node nn=new Node(item); nn.next=First; First=nn; } public void insertAtEnd(int item) { ptr=First; while(ptr.next!=null) ptr=ptr.next; Node nn=new Node(item); ptr.next=nn; } public void insertBefore(Node n,int item) { if(n==First) insertAtBeg(item); else { ptr=getPrevNode(n); Node nn=new Node(item,n); ptr.next=nn; } } public void insertBefore(int key,int item) { ptr=search(key); insertBefore(ptr,item); } public void insertAfter(int key,int item) { ptr=search(key); ptr=getNextNode(ptr); insertBefore(ptr,item); } public void delete(int item)
26
{ Node ptr2=search(item); if(ptr2!=null) if(isFirst(ptr2)) First=First.next; else { ptr=getPrevNode(ptr2); ptr.next=ptr2.next; } else System.out.println("Element not found"); } public void merge(LLoperation ob1,LLoperation ob2) { Node ptr1=ob1.First; while(ptr1.next!=null) ptr1=ptr1.next; ptr1.next=ob2.First; } public void copy(LLoperation l) { ptr=First; while(ptr!=null) { if(ptr==First) l.insertAtBeg(ptr.data); else l.insertAtEnd(ptr.data); ptr=ptr.next; } } public Node getLast() { ptr=First; while(ptr.next!=null) ptr=ptr.next; return ptr; } public void sort() { Node ptr1,ptr2,ptr3; int m,n; for(ptr1=getLast();ptr1!=First;ptr1=getPrevNode(ptr1)) for(ptr2=First;ptr2!=ptr1;ptr2=ptr2.next) { m=ptr2.data; n=ptr2.next.data; if(m>n) { ptr2.data=n; ptr2.next.data=m; } }}} class LLTest
27
{ public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the no of elments"); int n=Integer.parseInt(br.readLine()); LLoperation ll=new LLoperation(); ll.createLL(n); ll.traversal(); int t,k,m=1; do { System.out.println("Enter ur choice of operation"); System.out.println("1-insertAtBeg\n2-insertAtEnd\n3-insertAfter\n4-insertBefore\n5merge\n6-deleteItem\n7-sortLL\n8-copy\n0-exit"); n=Integer.parseInt(br.readLine()); switch(n) { case 1: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); ll.insertAtBeg(t); ll.traversal(); break; case 2: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); ll.insertAtEnd(t); ll.traversal(); break; case 3: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); System.out.println("Enter the element to insert after"); k=Integer.parseInt(br.readLine()); ll.insertAfter(k,t); ll.traversal(); break; case 4: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); System.out.println("Enter the element to insert berore"); k=Integer.parseInt(br.readLine()); ll.insertBefore(k,t); ll.traversal(); break; case 5: System.out.println("Enter the no of elements for new LList"); t=Integer.parseInt(br.readLine()); LLoperation LL=new LLoperation(); LL.createLL(t); LL.traversal(); ll.merge(ll,LL); System.out.println("The merged linked list is:");
28
case 6: System.out.println("Enter the element to be deleted"); t=Integer.parseInt(br.readLine()); ll.delete(t); ll.traversal(); break; case 7: ll.sort(); ll.traversal(); break; case 8: System.out.println("Copying"); LLoperation l2=new LLoperation(); l2.traversal(); ll.copy(l2); l2.traversal(); break; case 0: m=0; break; default: System.out.println("INVALID CHOICE"); } }while(m==1); ll.traversal(); } } Enter the no of elments 5 0 -> 10 -> 20 -> 30 -> 40 Enter ur choice of operation 1-insertAtBeg 2-insertAtEnd 3-insertAfter 4-insertBefore 5-merge 6-deleteItem 7-sortLL 8-copy 0-exit 1 Enter the element to be inserted 5 5 -> 0 -> 10 -> 20 -> 30 -> 40 Enter ur choice of operation 1-insertAtBeg 2-insertAtEnd 3-insertAfter 4-insertBefore 5-merge 6-deleteItem 7-sortLL 8-copy
ll.traversal(); break;
29
0-exit 2 Enter the element to be inserted 45 5 -> 0 -> 10 -> 20 -> 30 -> 40 -> 45 Enter ur choice of operation 1-insertAtBeg 2-insertAtEnd 3-insertAfter 4-insertBefore 5-merge 6-deleteItem 7-sortLL 8-copy 0-exit 6 Enter the element to be deleted 0 5 -> 10 -> 20 -> 30 -> 40 -> 45 Enter ur choice of operation 1-insertAtBeg 2-insertAtEnd 3-insertAfter 4-insertBefore 5-merge 6-deleteItem 7-sortLL 8-copy 0-exit 0 5 -> 10 -> 20 -> 30 -> 40 -> 45
30
{ if(isFull()) System.out.println("Stack is full"); else a[++top]=item; } int pop() { if(isEmpty()) //System.out.println("Stack is Empty"); return -999; else return a[top--]; } int peek() { if(!isEmpty()) return a[top]; System.out.println("Stack is Empty"); return 0; } void traversal() { for(int i=top;i>-1;i--) System.out.println(a[i]); System.out.println(); } } class StackArr { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the size of the stack"); int n=Integer.parseInt(br.readLine()); StackArrImp st=new StackArrImp(n); int k; do { System.out.println("Enter ur choice"); System.out.println("1-PUSH 2-POP 3-PEEK 0-EXIT"); n=Integer.parseInt(br.readLine()); switch(n) { case 1: System.out.println("Enter the element to push"); k=Integer.parseInt(br.readLine()); st.push(k); System.out.println("After push the stack is"); st.traversal(); break; case 2: st.pop(); System.out.println("After pop the stack is"); st.traversal();
31
break; case 3: case 0: System.out.println("The top element in the stack is :"+st.peek()); break;
break; default: System.out.println("INVALID CHOICE"); } }while(n!=0); }} Output: Enter the size of the stack 6 Enter ur choice 1-PUSH 2-POP 3-PEEK 0-EXIT 1 Enter the element to push 4 After push the stack is 4 Enter ur choice 1-PUSH 2-POP 3-PEEK 0-EXIT 1 Enter the element to push 3 After push the stack is 3 4 Enter ur choice 1-PUSH 2-POP 3-PEEK 0-EXIT 1 Enter the element to push 2 After push the stack is 2 3 4 Enter ur choice 1-PUSH 2-POP 3-PEEK 0-EXIT 2 After pop the stack is 3 4 Enter ur choice 1-PUSH 2-POP 3-PEEK 0-EXIT 3 The top element in the stack is :3 Enter ur choice 1-PUSH 2-POP 3-PEEK 0-EXIT
32
33
System.out.println(); } } class itop { String post[]; String ch; public String[] toPostfix(String in[]) { StackArrImp stk=new StackArrImp(in.length+1); post=new String[in.length]; int i,k=0; for(i=0;i<in.length;i++) { ch=in[i]; if(!isOperator(ch)) post[k++]=ch; else { if(ch.charAt(0)=='(') stk.push(ch); else if(ch.charAt(0)==')') { while(((String)stk.peek()).charAt(0)!='(') post[k++]=(String)stk.pop(); ch=((String)stk.pop()); } else { if(prec(ch)>prec((String)stk.peek())) stk.push(ch); else { while(prec(ch)<=prec((String)stk.peek())) post[k++]=(String)stk.pop(); stk.push(ch); } } } } while(!(((String)stk.peek()).charAt(0)=='#')) { post[k++]=(String)stk.pop(); } return post; } boolean isOperator(String ch1) { char ch=ch1.charAt(0); return (ch=='P'||ch=='A'||ch=='S'||ch=='M'||ch=='D'||ch=='('||ch==')'); }
34
int prec(String ch1) { char ch=ch1.charAt(0); int r=0; if(ch=='P') r=3; else if(ch=='M'||ch=='D') r=2; else if(ch=='A'||ch=='S') r=1; else if(ch=='#') r=0; return r; } void display(String post[]) { String ch1; for(int i=0;i<post.length&&post[i]!=null;i++) { ch1=post[i]; if(ch1.charAt(0)=='A') System.out.print("+"); else if(ch1.charAt(0)=='S') System.out.print("-"); else if(ch1.charAt(0)=='M') System.out.print("*"); else if(ch1.charAt(0)=='D') System.out.print("/"); else System.out.print(ch1.charAt(0)); } } void evaluate(String post[]) { StackArrImp stk=new StackArrImp(post.length+1); String ch1,ch2,ch3; for(int i=0;i<post.length&&post[i]!=null;i++) { ch1=post[i]; //stk.traversal(); if(isOperator(ch1)) { ch2=(String)stk.pop(); ch3=(String)stk.pop(); if(!isOperator(ch2)&&!isOperator(ch3)) { int m=Integer.parseInt(ch2); int n=Integer.parseInt(ch3); int k=0; if(ch1.charAt(0)=='A') k=m+n; else if(ch1.charAt(0)=='S')
35
k=n-m; else if(ch1.charAt(0)=='M') k=m*n; else if(ch1.charAt(0)=='D') k=n/m; stk.push(""+k); } } else { stk.push(ch1); //stk.traversal(); } } System.out.println("RESULT OF THE GIVEN EXPRESSION = "+stk.pop()); } } class Postfix { public static void main(String ar[]) throws IOException { itop obj=new itop(); System.out.println(""); System.out.print("Entered INFIX expression : "); obj.display(ar); System.out.println("\n"); String post1[]=obj.toPostfix(ar); System.out.print("POSTFIX of given INFIX is : "); obj.display(post1); System.out.println("\n"); obj.evaluate(post1); } } Output: D:\krish>java Postfix ( 3 A 4 ) M 5 Entered INFIX expression : (3+4)*5
/* Program 19: program to check the paranthesis(),{},<> are closed properly or not in a given string */
import java.io.*; class Node
36
{ char data; Node next; Node() { this(' '); } Node(char data) { this.data=data; next=null; } Node(char data,Node next) { this.data=data; this.next=next; } } class StackLLImp { Node top; void traversal() { Node ptr; ptr=top; while(ptr!=null) { System.out.println(ptr.data); ptr=ptr.next; } System.out.println(); } boolean isEmpty() { if(top==null) return true; return false; } char peek() { if(top!=null) return top.data; return '#'; } void push(char item) { Node nn=new Node(item,top); top=nn; } char pop() { if(top!=null) { char k=top.data; top=top.next;
37
return k; } else System.out.println("Stack is Empty"); return '#'; } int size() { int cnt=0; Node ptr=top; while(ptr!=null) { cnt++; ptr=ptr.next; } return cnt; }} class Parenthesis { static boolean isPair(char ch,char ch2) { if(ch=='('&&ch2==')') return true; if(ch=='{'&&ch2=='}') return true; if(ch=='<'&&ch2=='>') return true; return false; } public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StackLLImp st=new StackLLImp(); System.out.println("Enter the string to check"); String str=br.readLine(); int flag=0; char ch,ch2; for(int i=0;i<str.length();i++) { ch=str.charAt(i); if(ch=='('||ch=='{'||ch=='<') st.push(ch); else if(ch==')'||ch=='}'||ch=='>') { ch2=st.pop(); if(!isPair(ch2,ch)) { System.out.println("\nThe paranthesis "+ch2+" is not closed properly"); flag=1; } }} if(!st.isEmpty()) System.out.println("\nThe paranthesis "+st.pop()+" is not closed properly"); else
38
if(flag==0) System.out.println("\nAll the paranthesis are placed properly"); } } Output: Enter the string to check (a+{b*c)> The paranthesis { is not closed properly The paranthesis ( is not closed properly
/* Program 20: program to check whether a string is palindrome or not. (Using both Stack and Queue) */
import java.io.*; class Node { char data; Node next; Node() { this(' '); } Node(char data) { this.data=data; next=null; } Node(char data,Node next) { this.data=data; this.next=next; } } class StackLL { Node top; boolean isEmpty() { if(top==null) return true; return false; } void push(char item) { Node nn=new Node(item,top); top=nn; } char pop() { if(top!=null) { char k=top.data; top=top.next;
39
return k; } else System.out.println("Stack is Empty"); return '#'; } } class Que { Node front,rear; boolean isEmpty() { if(front==null) return true; return false; } void enqueue(char item) { Node nn=new Node(item); if(isEmpty()) front=rear=nn; else { rear.next=nn; rear=nn; } } char delqueue() { char k=' '; if(isEmpty()) System.out.println("Cannot delete,Queue is empty"); else if(front==rear) { k=front.data; front=rear=null; } else { k=front.data; front=front.next; } return k; } } class PalinTest { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StackLL st=new StackLL(); Que q=new Que(); System.out.println("Enter any string to check whether PALINDROME OR NOT"); String str=br.readLine();
40
int i,flag=0,l=str.length(); char ch1,ch2; for(i=0;i<l/2;i++) st.push(str.charAt(i)); i=(l+1)/2; while(i<l) { q.enqueue(str.charAt(i)); i++; } for(i=0;i<l/2;i++) if(st.pop()!=q.delqueue()) { flag=1; break; } if(flag==0) System.out.println("\n"+str+" is a PALINDROME"); else System.out.println("\n"+str+" is NOT A PALINDROME"); }} Output: Enter any string to check whether PALINDROME OR NOT MALAYALAM MALAYALAM is a PALINDROME
41
Node ptr; ptr=top; while(ptr!=null) { System.out.println(ptr.data); ptr=ptr.next; } System.out.println(); } boolean isEmpty() { if(top==null) return true; return false; } int peek() { if(top!=null) return top.data; return -999; } void push(int item) { Node nn=new Node(item,top); top=nn; } int pop() { if(top!=null) { int k=top.data; top=top.next; return k; } else System.out.println("Stack is Empty"); return -999; } int size() { int cnt=0; Node ptr=top; while(ptr!=null) { cnt++; ptr=ptr.next; } return cnt; }} class StackLL { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StackLLImp st=new StackLLImp();
42
System.out.println("Stack is created"); int k,n; do { System.out.println("Enter ur choice"); System.out.println("1-PUSH 2-POP 3-PEEK 0-EXIT"); n=Integer.parseInt(br.readLine()); switch(n) { case 1: System.out.println("Enter the element to push"); k=Integer.parseInt(br.readLine()); st.push(k); System.out.println("After push the stack is"); st.traversal(); break; case 2: st.pop(); System.out.println("After pop the stack is"); st.traversal(); break; case 3: if(st.peek()==-999) System.out.println("Stack is Empty"); else System.out.println("The top element in the stack is : "+st.peek()); break; case 0: break; default: System.out.println("INVALID CHOICE"); } }while(n!=0); }} Output: Stack is created Enter ur choice 1-PUSH 2-POP 3-PEEK 0-EXIT 1 Enter the element to push 10 After push the stack is 10 Enter ur choice 1-PUSH 2-POP 3-PEEK 0-EXIT 1 Enter the element to push 20 After push the stack is 20 10 Enter ur choice
43
1-PUSH 2-POP 3-PEEK 0-EXIT 2 After pop the stack is 10 Enter ur choice 1-PUSH 2-POP 3-PEEK 0-EXIT 3 The top element in the stack is : 10 Enter ur choice 1-PUSH 2-POP 3-PEEK 0-EXIT 0
44
return false; } void enqueue(int item) { Node nn=new Node(item); if(isEmpty()) front=rear=nn; else { rear.next=nn; rear=nn; } } int delqueue() { int k=0; if(isEmpty()) System.out.println("Cannot delete,Queue is empty"); else if(front==rear) { k=front.data; front=rear=null; } else { k=front.data; front=front.next; } return k; } int front() { return front.data; } } class QueueLL { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Que q=new Que(); int n,k; do { System.out.println("Enter ur choice"); System.out.println("1-ENQUEUE 2-DELQUEUE 3-FRONT 0-EXIT"); n=Integer.parseInt(br.readLine()); switch(n) { case 1: System.out.println("Enter the element to enqueue"); k=Integer.parseInt(br.readLine()); q.enqueue(k);
45
System.out.println("After enqueue the QUEUE is"); q.traversal(); break; case 2: q.delqueue(); System.out.println("After delqueue the QUEUE is"); q.traversal(); break; System.out.println("The front element in the QUEUE is :"+q.front()); break; case 0: break; default: System.out.println("INVALID CHOICE"); } }while(n!=0); }} Output: Enter ur choice 1-ENQUEUE 2-DELQUEUE 3-FRONT 0-EXIT 1 Enter the element to enqueue 5 After enqueue the QUEUE is 5 Enter ur choice 1-ENQUEUE 2-DELQUEUE 3-FRONT 0-EXIT 1 Enter the element to enqueue 6 After enqueue the QUEUE is 5 6 Enter ur choice 1-ENQUEUE 2-DELQUEUE 3-FRONT 0-EXIT 1 Enter the element to enqueue 8 After enqueue the QUEUE is 5 6 8 Enter ur choice 1-ENQUEUE 2-DELQUEUE 3-FRONT 0-EXIT 3 The front element in the QUEUE is :5 Enter ur choice 1-ENQUEUE 2-DELQUEUE 3-FRONT 0-EXIT 2 After delqueue the QUEUE is 6 8 Enter ur choice
case 3:
46
47
} public int deleteFirst() { if(!isEmpty()) { int k=dq[first]; for(int i=0;i<last;i++) dq[i]=dq[i+1]; last--; return k; } else System.out.println("Deque is empty"); return 0; } public int deleteLast() { if(!isEmpty()) return dq[last--]; else System.out.println("Deque is empty"); return 0; } public boolean isEmpty() { if(first==-1||last==-1) return true; return false; } public boolean isFull() { if(last==max-1) return true; return false; } } class DQARTest { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the size of the array"); int n=Integer.parseInt(br.readLine()); DEQueue dq=new DEQueue(n); int t,k,m=1; do {
48
System.out.println("Enter ur choice of operation"); System.out.println("1-insertFirst\n2-insertLast\n3-deleteFirst\n4-deleteLast\n0-exit"); n=Integer.parseInt(br.readLine()); switch(n) { case 1: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); dq.insertFirst(t); dq.traversal(); break;
case 2: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); dq.insertLast(t); dq.traversal(); break; case 3: dq.deleteFirst(); dq.traversal(); break; dq.deleteLast(); dq.traversal(); break;
case 4:
case 0:
m=0; break; default: System.out.println("INVALID CHOICE"); } }while(m==1); dq.traversal(); } } Output: Enter the size of the array 5 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 1 Enter the element to be inserted 5 5 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst
49
4-deleteLast 0-exit 1 Enter the element to be inserted 4 45 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 2 Enter the element to be inserted 6 456 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 2 Enter the element to be inserted 7 4567 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 3 567 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 4 56 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 0 56
50
int size(); void insertFirst(int item); void insertLast(int item); int deleteFirst(); int deleteLast();
class Dnode { int data; Dnode next; Dnode() { this(0); } Dnode(int data) { this.data=data; next=null; } Dnode(int data,Dnode next) { this.data=data; this.next=next; } } class DEQueue implements DQ { Dnode First,Last; void traversal() { Dnode ptr; ptr=First; while(ptr!=null) { System.out.print(ptr.data); ptr=ptr.next; if(ptr!=null) System.out.print(" -> "); } System.out.println(); } public int size() { int cnt=0; Dnode ptr; ptr=First; while(ptr!=null) { cnt++; ptr=ptr.next;
51
} return cnt; } public void insertFirst(int item) { Dnode nn=new Dnode(item,First); if(isEmpty()) Last=First=nn; else First=nn; } public void insertLast(int item) { Dnode nn=new Dnode(item,null); if(isEmpty()) Last=First=nn; else { Last.next=nn; Last=nn; } } public int deleteFirst() { if(!isEmpty()) { int k=First.data; if(First==Last) Last=First=null; else { First=First.next; return k; } } else System.out.println("Deque is empty"); return -999; } public int deleteLast() { if(!isEmpty()) { int k=Last.data; if(Last==First) Last=First=null; else { Dnode ptr=First; while(ptr.next!=Last)
52
ptr=ptr.next; Last=ptr; Last.next=null; return k; } } else System.out.println("Deque is empty"); return -999; } boolean isEmpty() { if(First==null||Last==null) return true; return false; } } class DLLTest { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); DEQueue dq=new DEQueue(); int n,t,k,m=1; do { System.out.println("Enter ur choice of operation"); System.out.println("1-insertFirst\n2-insertLast\n3-deleteFirst\n4-deleteLast\n0-exit"); n=Integer.parseInt(br.readLine()); switch(n) { case 1: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); dq.insertFirst(t); dq.traversal(); break;
case 2: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); dq.insertLast(t); dq.traversal(); break; case 3: dq.deleteFirst(); dq.traversal(); break; dq.deleteLast(); dq.traversal(); break;
case 4:
53
case 0: m=0; break; default: System.out.println("INVALID CHOICE"); } }while(m==1); dq.traversal(); } } Output: Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 1 Enter the element to be inserted 3 3 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 2 Enter the element to be inserted 4 3 -> 4 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 1 Enter the element to be inserted 2 2 -> 3 -> 4 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 3 3 -> 4 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast
54
55
Last.next=Last=nn; } } void traversal() { Dnode ptr; ptr=First; while(ptr!=null) { System.out.print(ptr.data); ptr=ptr.next; if(ptr!=null) System.out.print(" -> "); } System.out.println(); } public int size() { int cnt=0; Dnode ptr; ptr=First; while(ptr!=null) { cnt++; ptr=ptr.next; } return cnt; } Dnode search(int key) { Dnode ptr=First; while(ptr!=null) { if(ptr.data==key) return ptr; ptr=ptr.next; } return ptr; } public void insertFirst(int item) { Dnode nn=new Dnode(item,null,First); First.prev=nn; First=nn; } public void insertLast(int item) { Dnode nn=new Dnode(item,Last,null); Last.next=nn; Last=nn; }
56
public int deleteFirst() { int k=First.data; if(!isEmpty()) if(First==Last) Last=First=null; else { First=First.next; First.prev=null; return k; } return -999; } public int deleteLast() { int k=Last.data; if(!isEmpty()) if(Last==First) Last=First=null; else { Last=Last.prev; Last.next=null; return k; } return -999; } boolean isEmpty() { if(First==null||Last==null) return true; return false; } } class DQDLLTest { public static void main(String ar[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the no of elments"); int n=Integer.parseInt(br.readLine()); DEQueue dq=new DEQueue(); dq.createLL(n); dq.traversal(); int t,k,m=1; do { System.out.println("Enter ur choice of operation"); System.out.println("1-insertFirst\n2-insertLast\n3-deleteFirst\n4-deleteLast\n0-exit"); n=Integer.parseInt(br.readLine());
57
switch(n) { case 1: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); dq.insertFirst(t); dq.traversal(); break; case 2: System.out.println("Enter the element to be inserted"); t=Integer.parseInt(br.readLine()); dq.insertLast(t); dq.traversal(); break; dq.deleteFirst(); dq.traversal(); break; dq.deleteLast(); dq.traversal(); break;
case 3:
case 4:
case 0:
m=0; break; default: System.out.println("INVALID CHOICE"); } }while(m==1); dq.traversal(); } } Output: Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 1 Enter the element to be inserted 5 5 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 1 Enter the element to be inserted 6
58
6 -> 5 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 2 Enter the element to be inserted 4 6 -> 5 -> 4 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 2 Enter the element to be inserted 3 6 -> 5 -> 4 -> 3 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 4 6 -> 5 -> 4 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 3 5 -> 4 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 4 5 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 3 Enter ur choice of operation 1-insertFirst
59
2-insertLast 3-deleteFirst 4-deleteLast 0-exit 4 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 3 Enter ur choice of operation 1-insertFirst 2-insertLast 3-deleteFirst 4-deleteLast 0-exit 0
60
{ if( newNode.prn < p.prn ) { nodeBefore = p; break; } else { prev = p; p = p.next; } } newNode.next = nodeBefore; 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 LinkedPriorityQueueDemo { public static void main(String[] args) { LinkedPriorityQueue pq = new LinkedPriorityQueue(); Node item; pq.insert("kumar", 3); pq.insert("anil", 2); pq.insert("Kishor", 2); pq.insert("Ravi", 1); pq.insert("Siva", 3); pq.displayList(); item = pq.delete();
61
if( item != null ) System.out.println("delete():" + item.data + "(" +item.prn+")"); pq.displayList(); pq.insert("Arnold", 2); pq.insert("Neeru", 1); pq.insert("Hasini", 4); pq.displayList(); } } Output: Queue: Ravi(1) anil(2) Kishor(2) kumar(3) Siva(3) delete():Ravi(1) Queue: anil(2) Kishor(2) kumar(3) Siva(3) Queue: Neeru(1) anil(2) Kishor(2) Arnold(2) kumar(3) Siva(3) Hasini(4)
62
BSTNode inorderSucc; if(root == null) { System.out.println("Tree is empty"); return null; } p = root; /* find node being deleted & its parent */ 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; } /* find inorder successor of the node being deleted and its parent */ if(p.left != null && p.right != null) // case-3 { 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) // case-1 { if( parent.left == p ) parent.left = null; else parent.right = null; } if(p.left == null && p.right != null) // case-2(a) { if(parent.left == p) parent.left = p.right; else parent.right = p.right; } if(p.left != null && p.right == null) // case-2(b) { if(parent.left == p) parent.left = p.left; else parent.right = p.left; } return root; } public void inorder(BSTNode p) // 'p' starts with root { if( p != null ) { inorder(p.left); System.out.print(p.data + " "); inorder(p.right); } } }
63
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]); System.out.print("\n Inorder: "); bst.inorder(root); int key = 55; // delete 55 bst.deleteTree(root, key); System.out.print("\n Inorder, after deletion of " + key + ": "); bst.inorder(root); key = 44; // insert 44 bst.insertTree(root, key); System.out.print("\n Inorder, after insertion of " + key + ": "); bst.inorder(root); BSTNode root2 = root; // copy BST key = 66; System.out.print("\n\n Searching 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"); }} Output: Inorder: 10 15 20 25 30 45 50 55 60 65 75 80 Inorder, after deletion of 55: 10 15 20 25 30 45 50 60 65 75 80 Inorder, after insertion of 44: 10 15 20 25 30 44 45 50 60 65 75 80 Searching 66..... Node 66 not found
64
} boolean isfull() { if(rear==n-1) return true; return false; } void inseque(int item) { if(isfull()) { System.out.println("queue is full"); } else { nl=(rear+1)%n; if(isempty()) { front=rear=0; data[rear]=item; } else { rear=nl; data[rear]=item; } } } int deleque() { if(isempty()) { System.out.println("queue is empty"); return-1; } else { int item=data[front]; if(front==rear) front=rear=-1; else { nl=(front+1)%n; front=nl; } return item; } } int size() { int i=front,c=0; while(i!=rear) { c++;
65
} c++; return c; } int getfront() { if(!isempty()) return data[front]; return-1; } void display() { int l=front; while(l!=rear) { System.out.println(data[l]); l=(l+1)%n; System.out.println(data[l]); } } } public class Clrque { public static void main(String[] args)throws IOException { int a,b,c,d; Cque Cq=new Cque(7); Cq.inseque(123); Cq.inseque(345); Cq.inseque(45); System.out.println("elements are"); Cq.display(); a=Cq.getfront(); System.out.println("front" + a); d=Cq.size(); System.out.println("size" + d); b=Cq.deleque(); System.out.println("delete" + b); c=Cq.getfront(); System.out.println("front=" + c); } } Output: elements are 123 345 345 45 front123 size3 delete123 front=345
nl=(i+1)%n; i=nl;
66
//27 Program to traverse Binary Tree using //a)INORDER b)PREORDER c)POSTORDER techniques
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]; 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; } /* Recursive methods - Binary tree traversals */ 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 + " ");
67
} } /* Non-recursive methods - Binary tree traversals */ public void preorderIterative(Node p) { if(p == null ) { System.out.println("Tree is empty"); return; } stk.push(p); while( !stk.isEmpty() ) { 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 ))
68
{ System.out.print(p.data + " "); tmp = p; if( stk.isEmpty() ) return; p = stk.pop(); } stk.push(p); p = p.right; } } } class BinaryTreeTraversals { 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); } } Output: Recursive Binary Tree Traversals: inorder: A B C D E F G H preorder: E C A B D G F H postorder: B A D C F H G E Non-recursive Binary Tree Traversals: inorder: A B C D E F G H preorder: E C A B D G F H postorder: B A D C F H G E
69
{ int i, pass, exch, n = a.length; int tmp; for( pass = 0; pass < n; pass++ ) { exch = 0; for( i = 0; i < n-pass-1; i++ ) if( ((Comparable)a[i]).compareTo(a[i+1]) > 0) { tmp = a[i]; a[i] = a[i+1]; a[i+1] = tmp; exch++; } if( exch == 0 ) return; } } void selectionSort( int a[] ) { int n = a.length; for( int pass = 0; pass < n-1; pass++ ) { int min = pass; for( int i = pass+1; i < n; i++ ) if( a[i] < a[min] ) min = i; if( min != pass ) { int tmp = a[min]; a[min] = a[pass]; a[pass] = tmp; } } } void display( int a[] ) { for( int i = 0; i < a.length; i++ ) System.out.print( a[i] + " " ); } void insertionSort(int a[]) { int i, j, n = a.length; int item; for( j = 1; j < n; j++ ) { item = a[j]; i = j-1; while( i >= 0 && ((Comparable)item).compareTo(a[i]) < 0) { a[i+1] = a[i]; i = i-1; } a[i+1] = item; } }
70
void quickSort(int a[], int left, int right) { int newleft = left, newright = right; int amid, tmp; amid = a[(left + right)/2]; do { while( (a[newleft] < amid) && (newleft < right)) newleft++; while( (amid < a[newright]) && (newright > left)) newright--; if(newleft <= newright) { tmp = a[newleft]; a[newleft] = a[newright]; a[newright] = tmp; newleft++; newright--; } } while(newleft <= newright); if(left < newright) quickSort(a, left, newright); if(newleft < right) quickSort(a, newleft, right); } void radixSort(int[] arr, int radix, int maxDigits) { int d, j, k, m, divisor; java.util.LinkedList[] queue = new java.util.LinkedList[radix]; for( d = 0; d < radix; d++ ) queue[d] = new java.util.LinkedList(); divisor = 1; for(d = 1; d <= maxDigits; d++) { for(j = 0; j < arr.length; j++) { m = (arr[j]/divisor) % radix; queue[m].addLast(new Integer(arr[j])); } divisor = divisor*radix; for(j = k = 0; j < radix; j++) { while( !queue[j].isEmpty()) arr[k++] = (Integer)queue[j].removeFirst(); }} } } class MergeSort { int[] a; int[] tmp; MergeSort(int[] arr) { a = arr; tmp = new int[a.length]; } void msort() { sort(0, a.length-1); }
71
void sort(int left, int right) { if(left < right) { int mid = (left+right)/2; sort(left, mid); sort(mid+1, right); merge(left, mid, right); } } void merge(int left, int mid, int right) { int i = left; int j = left; int k = mid+1; while( j <= mid && k <= right ) { if(a[j] < a[k]) tmp[i++] = a[j++]; else tmp[i++] = a[k++]; } while( j <= mid ) tmp[i++] = a[j++]; for(i=left; i < k; i++) a[i] = tmp[i]; } } class Heap { int[] a; int maxSize; int currentSize; public Heap(int m) { maxSize = m; currentSize = 0; a = new int[maxSize]; } public boolean insert(int key) { if(currentSize == maxSize) return false; a[currentSize] = key; moveUp(currentSize++); return true; } public void moveUp(int index) { int parent = (index-1)/2; int bottom = a[index]; while(index > 0 && a[parent] < bottom) { a[index] = a[parent]; index = parent; parent = (parent-1)/2; } a[index] = bottom; } public int remove()
72
{ if( isEmpty() ) { System.out.println("Heap is empty"); return -1; } int root = a[0]; a[0] = a[--currentSize]; moveDown(0); return root; } public void moveDown(int index) { int largerChild; int top = a[index]; while(index < currentSize/2) { int leftChild = 2*index+1; int rightChild = 2*index+2; if(rightChild<currentSize && a[leftChild]<a[rightChild]) largerChild = rightChild; else largerChild = leftChild; if(top >= a[largerChild]) break; a[index] = a[largerChild]; index = largerChild; } a[index] = top; } public boolean isEmpty() { return currentSize==0; } void heapsort(int []arr) { Heap h = new Heap(arr.length); for(int i = 0; i < arr.length; i++) h.insert(arr[i]); for( int i = arr.length-1; i >= 0; i-- ) arr[i] = h.remove(); } } class SortDemo { public static void main(String[] args) throws IOException { int[] arr = {75, 40, 10, 90, 50, 95, 55, 15, 65}; System.out.println("Enter ur choice of sort"); System.out.println("1-Bubblesort\n2-Selection sort\n3-Insertion sort\n4-Quicksort\n5Merge sort\n6-Heapsort\n7-Radix sort"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); SortingMethods obj= new SortingMethods(); System.out.print("\n Unsorted array: "); obj.display( arr ); switch(n) { case 1: obj.bubbleSort(arr); break; case 2: obj.selectionSort( arr ); break; case 3: obj.insertionSort(arr);
73
break; case 4: obj.quickSort( arr, 0, arr.length-1 ); break; case 5: MergeSort ms=new MergeSort(arr); ms.msort(); break; case 6: Heap hs=new Heap(9); hs.heapsort(arr); break; case 7: obj.radixSort(arr,9,4); break; } System.out.print("\n Sorted array: "); obj.display( arr ); } } Output: Enter ur choice of sort 1-Bubblesort 2-Selection sort 3-Insertion sort 4-Quicksort 5-Merge sort 6-Heapsort 7-Radix sort 3 Unsorted array: 75 40 10 90 50 95 55 15 65 Sorted array: 10 15 40 50 55 65 75 90 95
74
} return p; } public void levelorder(Node p) { que.addLast(p); while( !que.isEmpty() ) { p = que.removeFirst(); System.out.print(p.data + " "); if(p.left != null) que.addLast(p.left); if(p.right != null) que.addLast(p.right); } } } class LevelOrderTraversal { 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 Level Order Tree Traversal: "); t.levelorder(root); } Output: Level Order Tree Traversal: E C G A D F H B
75
int count = 0; if( p != null) { if((p.left == null) && (p.right == null)) count = 1; else count = count + leafNodes(p.left) + leafNodes(p.right); } return count; } public void inorder(BSTNode p) { if( p != null ) { inorder(p.left); System.out.print(p.data + " "); inorder(p.right); } } } 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; System.out.print("\n Number of leaf nodes: " + bst.leafNodes(root)); System.out.print("\n Inorder: "); bst.inorder(root); int key = 44; bst.insertTree(root, key); System.out.print("\n Inorder, after insertion of " + key + ": "); bst.inorder(root); }} Output: Number of leaf nodes: 6 Inorder: 10 15 20 25 30 45 50 55 60 65 75 80 Inorder, after insertion of 44: 10 15 20 25 30 44 45 50 55 60 65 75 80
76