Ads Lab Record
Ads Lab Record
Roll No :_______________________
1. Write Java programs that use both recursive and non-recursive functions for
import java.io.*;
class LinearSearch
int count=0;
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
int key=Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
{
if(arr[i]==key)
else
count++;
if(count==n)
OUTPUT:
//Linear Search using recursive function
import java.io.*;
class RecursiveLinearSearch
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
arr=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
key=Integer.parseInt(br.readLine());
if( linearSearch(arr.length-1) )
else
if(key == arr[n])
return true;
else
return linearSearch(n-1);
OUTPUT:
1 (b) Binary Search using non-recursive function
class BinarySearch
static Object[] a = { "AP", "KA", "MH", "MP", "OR", "TN", "UP", "WB"};
if( binarySearch() )
else
c = ((Comparable)key).compareTo(a[mid]);
return false;
OUTPUT:
//Binary Search using recursive function
import java.io.*;
class RecursiveBinarySearch
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
arr=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
key=Integer.parseInt(br.readLine());
else
int c = ((Comparable)key).compareTo(arr[mid]);
if( c < 0) return binarySearch(low, mid-1);
OUTPUT:
Laboratory Record Experiment No:__________________
Roll No :_______________________
2. Write Java programs to implement the following using arrays and linked lists
List ADT
//List.java
// ArrayList.java
class Node
Object data;
int next;
data = ob;
next = i;
MAXSIZE = s;
int p;
count++;
}
public void insertFirst(Object item)
System.out.println("***List is FULL");
return;
int p = getNode();
if( p != -1 )
list[p].data = item;
head = p;
count++;
System.out.println("***List is FULL");
return;
if( q != -1 )
list[q].data = item;
list[q].next = list[p].next;
list[p].next = q;
count++;
if(list[p].data == null)
return p;
return -1;
public int find(Object ob) // find the index (position) of the Object ob
int p = head;
while( p != -1)
return -1;
if( isEmpty() )
return null;
}
else
head = list[head].next;
return tmp;
int p = find(x);
if( p == -1 || list[p].next == -1 )
System.out.println("No deletion");
return null;
int q = list[p].next;
list[p].next = list[q].next;
count--;
return tmp;
int p = head;
System.out.print("\nList: [ " );
while( p != -1)
System.out.println("]\n");//
return count;
// ArrayListDemo.java
class ArrayListDemo
linkedList.initializeList();
System.out.print("InsertFirst 55:");
linkedList.insertFirst(55);
linkedList.display();
linkedList.display();
System.out.print("InsertFirst 77:");
linkedList.insertFirst(77);
linkedList.display();
linkedList.display();
OUTPUT:
b) List Using LinkedList //LinkedListDemo.java
class Node
data = d;
count++;
if( p == null )
count++;
p = head;
if( isEmpty() )
return null;
head = tmp.next;
count--;
return tmp.data;
if( p == null )
return null;
System.out.println("No deletion");
return null;
else
count--;
}
public boolean isEmpty() // true if list is empty
return count;
class LinkedListDemo
list.displayList();
list.displayList();
list.displayList();
list.displayList();
list.displayList();
}
OUTPUT:
Laboratory Record Experiment No:__________________
Roll No :_______________________
import java.io.*;
class stackclass
int top,ele,stack[],size;
stackclass(int n)
stack=new int[n];
size=n;
top= -1;
void push(int x)
ele=x;
stack[++top]=ele;
int pop()
if(!isempty())
else
System.out.println("stack is empty");
return -1;
boolean isempty()
if(top==-1)
return true;
else
return false;
boolean isfull()
if(size>(top+1))
return false;
else
return true;
int peek()
if(!isempty())
return stack[top];
else
System.out.println("stack is empty");
return -1;
}
}
void size()
void display()
if(!isempty())
for(int i=top;i>=0;i--)
System.out.print(stack[i]+" ");
else
System.out.println("stack is empty");
class stacktest
int size=Integer.parseInt(br.readLine());
int ch,ele;
do
System.out.println();
System.out.println("1.push");
System.out.println("2.pop");
System.out.println("3.peek");
System.out.println("4.size");
System.out.println("5.display");
System.out.println("6.is empty");
System.out.println("7.is full");
System.out.println("8.exit");
ch=Integer.parseInt(br.readLine());
switch(ch)
case 1:if(!s.isfull())
ele=Integer.parseInt(br.readLine());
s.push(ele);
else
System.out.print("stack is overflow");
break;
if(del!=-1)
System.out.println(del+" is deleted");
break;
if(p!=-1)
break;
case 4:s.size();
break;
case 5:s.display();
break;
System.out.println(b);
break;
System.out.println(b1);
break;
case 8 :System.exit(1);
}while(ch!=0);
OUTPUT:
3(b)Queue ADT using array
import java.util.*;
class queue
int front,rear;
int que[];
int max,count=0;
queue(int n)
max=n;
que=new int[max];
front=rear=-1;
boolean isfull()
if(rear==(max-1))
return true;
else
return false;
boolean isempty()
if(front==-1)
return true;
else
return false;
void insert(int n)
if(isfull())
System.out.println("list is full");
else
rear++;
que[rear]=n;
if(front==-1)
front=0;
count++;
int delete()
int x;
if(isempty())
return -1;
else
x=que[front];
que[front]=0;
if(front==rear)
front=rear=-1;
else
front++;
count--;
return x;
void display()
if(isempty())
System.out.println("queue is empty");
else
for(int i=front;i<=rear;i++)
System.out.println(que[i]);
int size()
return count;
int ch;
System.out.println("enter limit");
int n=s.nextInt();
do
System.out.println("1.insert");
System.out.println("2.delete");
System.out.println("3.display");
System.out.println("4.size");
ch=s.nextInt();
switch(ch)
int n1=s.nextInt();
q.insert(n1);
break;
if(c1>0)
System.out.println("deleted element is :"+c1);
else
System.out.println("can't delete");
break;
case 3:q.display();
break;
break;
while(ch!=0);
OUTPUT:
Laboratory Record Experiment No:__________________
Roll No :_______________________
4. Write a java program that reads an infix expression, converts the expression
to postfix form and then evaluates the postfix expression (use stack ADT).
import java.io.*;
class InfixToPostfix
ch = infix.charAt(i);
if( isOperator(item) )
stk.push(item);
stk.push(ch);
else
stk.push(ch);
else
stk.push(item);
stk.push(ch);
} // end of if(isOperator(ch))
if( ch == ')' )
item = stk.pop();
item = stk.pop();
} // end of for-loop
return postfix;
return rank;
//InfixToPostfixDemo.java
class InfixToPostfixDemo
System.out.println("Enter Expression:");
System.out.println("postfix:"+obj.toPostfix(infix) );
OUTPUT:
Laboratory Record Experiment No:__________________
Roll No :_______________________
import java.util.*;
class CirQue
int front,rear,next=0;
int que[];
int max,count=0;
CirQue(int n)
max=n;
que=new int[max];
front=rear=-1;
boolean isfull()
if(front==(rear+1)%max)
return true;
else
return false;
boolean isempty()
if(front==-1&&rear==-1)
return true;
else
return false;
int delete()
if(isempty())
return -1;
else
count --;
int x=que[front];
if(front==rear)
front=rear=-1;
else
next=(front+1)%max;
front=next;
return x;
}}
if(isempty())
que[++rear]=item;
front=rear;
count ++;
else if(!isfull())
{
next=(rear+1)%max;
if(next!=front)
que[next]=item;
rear=next;
count ++;
else
System.out.println("q is full");
void display()
if(isempty())
System.out.println("queue is empty");
else
next=(front)%max;
while(next<=rear)
System.out.println(que[next]);
next++;
int size()
return count;
int ch;
int n=s.nextInt();
do
{ System.out.println("1.insert");
System.out.println("2.delete");
System.out.println("3.display");
System.out.println("4.size");
ch=s.nextInt();
switch(ch)
int n1=s.nextInt();
q.insert(n1);
break;
if(c1>0)
else
System.out.println("can't delete");
break;
case 3:q.display();
break;
break;
while(ch!=0);
}
OUTPUT:
Laboratory Record Experiment No:__________________
Roll No :_______________________
6. Write a Java program that uses both a stack and a queue to test whether the given string is a palindrome or
not.
import java.util.Stack;
import java.io.*;
class PalindromeST
System.out.println("Enter String:");
if( isPalindrome(str) )
else
stk.push(str.charAt(i));
return false;
return true;
OUTPUT:
import java.util.LinkedList;
import java.io.*;
class PalindromeQ
System.out.println("Enter String:");
if( isPalindrome(str) )
else
}
static boolean isPalindrome(String str)
int n = str.length();
que.addLast(str.charAt(i));
return false;
return true;
OUTPUT:
Laboratory Record Experiment No:__________________
Roll No :_______________________
7. Write Java programs to implement the following using a singly linked list.
(a) Stack ADT
(b) Queue ADT
import java.io.*;
class Stack1
Stack1 top,next,prev;
int data;
Stack1()
data=0;
next=prev=null;
Stack1(int d)
data=d;
next=prev=null;
void push(int n)
Stack1 nn;
nn=new Stack1(n);
if(top==null)
top=nn;
else
nn.next=top;
top.prev=nn;
top=nn;
int pop()
int k=top.data;
if(top.next==null)
top=null;
return k;
else
top=top.next;
top.prev=null;
return k;
boolean isEmpty()
if(top==null)
return true;
else
return false;
void display()
{
Stack1 ptr;
for(ptr=top;ptr!=null;ptr=ptr.next)
System.out.print(ptr.data+" ");
int x;
int ch;
do{
ch=Integer.parseInt(b.readLine());
switch(ch)
int e=Integer.parseInt(b.readLine());
a.push(e);
break;
case 2:if(!a.isEmpty())
int p=a.pop();
else
{
System.out.println("stack is empty");
break;
case 3:System.out.println(a.isEmpty());
break;
case 4:if(!a.isEmpty())
a.display();
else
System.out.println("list is empty");
}while(ch!=0);
OUTPUT:
7 (b). Queue
import java.io.*;
class Qlnk
Qlnk front,rear,next;
int data;
Qlnk()
data=0;
next=null;
Qlnk(int d)
data=d;
next=null;
Qlnk getFront()
return front;
Qlnk getRear()
return rear;
Qlnk nn;
nn=new Qlnk(item);
if(isEmpty())
front=rear=nn;
else
rear.next=nn;
rear=nn;
int delelm()
if(isEmpty())
System.out.println("deletion failed");
return -1;
}
else
int k=front.data;
if(front!=rear)
front=front.next;
else
rear=front=null;
return k;
boolean isEmpty()
if(rear==null)
return true;
else
return false;
int size()
Qlnk ptr;
int cnt=0;
for(ptr=front;ptr!=null;ptr=ptr.next)
cnt++;
return cnt;
void display()
Qlnk ptr;
if(!isEmpty())
for(ptr=front;ptr!=null;ptr=ptr.next)
System.out.print(ptr.data+" ");
else
System.out.println("q is empty");
int ch;
do
System.out.println("enter ur choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
int item=Integer.parseInt(br.readLine());
m.insertelm(item);break;
}while(ch!=0);
OUTPUT:
Laboratory Record Experiment No:__________________
Roll No :_______________________
8. Write Java programs to implement the deque (double ended queue) ADT using
class ArrayDeque
maxSize = s;
count = 0;
if(count == maxSize)
System.out.println("Deque is full");
return;
}
que[last] = item;
first = 0;
count++;
if(count == 0)
System.out.println("Deque is empty");
return(' ');
if(last > 0)
count--;
if(count == 0)
return(item);
if(count == maxSize)
if(first > 0)
first = maxSize-1;
que[first] = item;
count++;
if(count == 0)
System.out.println("Deque is empty");
return(' ');
if(first == maxSize-1)
first = 0;
else
count--;
if(count == 0)
return(item);
void display()
System.out.println("----------------------------");
System.out.println(" 0 1 2 3 4 5");
System.out.print("Deque: ");
System.out.println("\n----------------------------");
class ArrayDequeDemo
q1.insertLast('A'); /* (a) */
q1.insertLast('B');
q1.insertLast('C');
q1.insertLast('D');
System.out.println("deleteFirst():"+q1.deleteFirst());
q1.display();
q1.insertLast('E'); /* (b) */
q1.display();
/* (c) */
System.out.println("deleteLast():"+q1.deleteLast());
System.out.println("deleteLast():"+q1.deleteLast());
q1.display();
q1.insertFirst('P');
q1.insertFirst('Q'); /* (d) */
q1.insertFirst('R');
q1.display();
q1.deleteFirst();
q1.display(); /* (e) */
q1.insertFirst('X');
q1.display(); /* (f) */
q1.insertLast('Y');
q1.display(); /* (g) */
q1.insertLast('Z');
q1.display(); /* (h) */
OUTPUT:
8 (c) Deque using dll
class LinkedDeque
DequeNode prev;
Object data;
DequeNode next;
data = item;
if( isEmpty() )
else
tmp.next = first;
first.prev = tmp;
first = tmp;
count++;
if( isEmpty() )
first = last = new DequeNode(item);
else
tmp.prev = last;
last.next = tmp;
last = tmp;
count++;
if( isEmpty() )
System.out.println("Deque is empty");
return null;
else
first = first.next;
first.prev = null;
count--;
return item;
if( isEmpty() )
System.out.println("Deque is empty");
return null;
else
last = last.prev;
last.next = null;
count--;
return item;
if( !isEmpty() )
return( first.data );
else
return null;
if( !isEmpty() )
return( last.data );
return(count);
}
DequeNode p = first;
System.out.print("Deque: [ ");
while( p != null )
p = p.next;
System.out.println("]");
class LinkedDequeDemo
System.out.println("removeFirst():" + dq.removeFirst());
dq.addFirst('A');
dq.addFirst('B');
dq.addFirst('C');
dq.display();
dq.addLast('D');
dq.addLast('E');
System.out.println("getFirst():" + dq.getFirst());
System.out.println("getLast():" + dq.getLast());
dq.display();
System.out.println("removeFirst():"+dq.removeFirst());
System.out.println("removeLast():"+ dq.removeLast());
dq.display();
System.out.println("size():" + dq.size());
}
OUTPUT:
Laboratory Record Experiment No:__________________
Roll No :_______________________
// LinkedPriorityQueueDemo.java
class Node
data = str;
prn = p;
class LinkedPriorityQueue
public void insert(String item, int pkey) // insert item after pkey
int k;
else k = 3;
switch( k )
{
head.next = null;
break;
head = newNode;
newNode.next = oldHead;
break;
Node prev = p;
while( p != null )
nodeBefore = p;
break;
else
} // end of while
newNode.next = nodeBefore;
prev.next = newNode;
} // end of switch
if( isEmpty() )
{
System.out.println("Queue is empty");
return null;
else
head = head.next;
return tmp;
System.out.print("\nQueue: ");
System.out.println();
return head;
}
class LinkedPriorityQueueDemo
Node item;
pq.insert("Babu", 3);
pq.insert("Nitin", 2);
pq.insert("Laxmi", 2);
pq.insert("Kim", 1);
pq.insert("Jimmy", 3);
pq.displayList();
item = pq.delete();
pq.displayList();
pq.insert("Scot", 2);
pq.insert("Anu", 1);
pq.insert("Lehar", 4);
pq.displayList();
} }
OUTPUT:
Laboratory Record Experiment No:__________________
Roll No :_______________________
import java.util.*;
class Bstnode
Bstnode rc,lc;
Bstnode root;
int data;
Bstnode()
data=0;
rc=lc=null;
Bstnode(int item)
data=item;
lc=rc=null;
par=null;
while(ptr!=null)
if(ptr.data==key)
b[0]=par;
b[1]=ptr;
return b;
else if(ptr.data<key)
par=ptr;
ptr=ptr.rc;
else
par=ptr;
ptr=ptr.lc;
b[0]=par;b[1]=ptr;
return b;
arr=search(item);
if(root!=null)
{
Bstnode par=arr[0];
Bstnode ptr=arr[1];
if(ptr!=null)
else
if(par.data<item)
par.rc=nn;
else
par.lc=nn;
else
root=nn;
if(ptr!=null)
inorder(ptr.lc);
System.out.println(ptr.data);
inorder(ptr.rc);
if(ptr!=null)
System.out.println(ptr.data);
inorder(ptr.lc);
inorder(ptr.rc);
}
if(ptr!=null)
inorder(ptr.lc);
inorder(ptr.rc);
System.out.println(ptr.data);
if(par!=null)
if(par.lc==ptr)
par.lc=null;
else
par.rc=null;
else
root=null;
return ptr.data;
if(par!=null)
if(par.lc==ptr)
if(ptr.lc==null)
par.lc=ptr.rc;
else
par.lc=ptr.lc;
else if(par.rc==ptr)
if(ptr.lc==null)
par.rc=ptr.rc;
else
par.rc=ptr.lc;
else
if(ptr.rc!=null)
root=ptr.rc;
else
root=ptr.lc;
return ptr.data;
Bstnode ptr1=ptr.rc;
Bstnode par1=null;
while(ptr1.lc!=null)
par1=ptr1;
ptr1=ptr1.lc;
if(par1!=null)
{
if(ptr1.rc!=null)
par1.lc=ptr1.rc;
else
par1.lc=null;
ptr1.lc=ptr.lc;
ptr1.rc=ptr.rc;
else // if par1=null
ptr1.lc = ptr.lc;
if(par!=null)
if(par.lc==ptr)
par.lc=ptr1;
else
par.rc=ptr1;
else
root=ptr1;
return ptr.data;
Bstnode ptr=root,par=null;
boolean flag=false;
int k;
while(ptr!=null&&flag==false)
if(item<ptr.data)
par=ptr;
ptr=ptr.lc;
else if(item>ptr.data)
par=ptr;
ptr=ptr.rc;
else
ptr.data=item;
flag=true;
if(flag==false)
return -1;
if(ptr.lc==null&&ptr.rc==null)
k=deleteleaf(par,ptr);
else if(ptr.lc!=null&&ptr.rc!=null)
k=delete2childnode(par,ptr);
else
k=delete1childnode(par,ptr);
return k;
int ch;
do
System.out.println("1.insert");
System.out.println("2.delete");
System.out.println("3.search");
System.out.println("4.inorder");
System.out.println("5.preorder");
System.out.println("6.postorder");
System.out.print("enter ur choice:");
ch=s.nextInt();
switch(ch)
int n=s.nextInt();
b.insert(n);
break;
case 2:if(b.root!=null)
System.out.print("enter element:");
int n1=s.nextInt();
int res=b.deletenode(n1);
if(res!=-1)
else
break;
case 3:if(b.root!=null)
int key=s.nextInt();
Bstnode search1[]=new Bstnode[2];
search1=b.search(key);
if(search1[1]!=null)
System.out.println("key is found");
else
if(search1[0]!=null)
if(search1[1]!=null)
else
else
break;
case 4:if(b.root!=null)
b.inorder(b.root);
else
break;
case 5:if(b.root!=null)
b.preorder(b.root);
else
break;
case 6:if(b.root!=null)
b.postorder(b.root);
else
}while(ch!=0);
OUTPUT:
Laboratory Record Experiment No:__________________
11. Write a Java program to implement all the functions of a dictionary (ADT) using Hashing.
// Dictionary.java
class Entry
key = k;
element = e;
class HashTable
size = s;
count = 0;
hashArray = new Entry[size];
int hashFunc( String theKey ) // convert the string into a numeric key
int hashVal=0;
if(hashVal < 0 )
return hashVal;
if( !isFull() )
while(hashArray[hashVal] != null )
else
System.out.println("Table is full");
if( !isEmpty() )
count--;
else
System.out.println("Table is empty");
return null;
if(hashArray[i] != null )
return count == 0;
return count;
class Dictionary
ht.insert("man", "gentleman");
ht.insert("watch", "observe");
ht.insert("hope", "expect");
ht.insert("run", "sprint");
ht.insert("wish", "desire");
ht.insert("format", "arrangement");
// Search an item
else
// Delete an item
word = "hope";
item = ht.delete(word);
else
} }
OUTPUT:
11 (b): Dictionary operations using java.util.Hashtable
import java.util.*;
class HashtableDemo
htab.put("man", "gentleman");
htab.put("watch", "observe");
htab.put("hope", "expect");
htab.put("run", "sprint");
htab.put("wish", "desire");
htab.put("format", "arrangement");
System.out.println(htab.entrySet());
}
OUTPUT:
Laboratory Record Experiment No:__________________
12.Write a java program to implement Dijkstras algorithmfor single shortest path problem
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Edge
class Dijkstra1
source.minDistance = 0.;
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
Vertex v = e.target;
vertexQueue.remove(v);
v.minDistance = distanceThroughU ;
v.previous = u;
vertexQueue.add(v);
}
public static List<Vertex> getShortestPathTo(Vertex target)
path.add(vertex);
Collections.reverse(path);
return path;
new Edge(v3, 8) };
new Edge(v4, 7) };
new Edge(v1, 3) };
new Edge(v4, 2) };
new Edge(v3, 2) };
OUTPUT:
Laboratory Record Experiment No:__________________
13. Write Java programs that use recursive and non-recursive functions to traverse the given binary tree in
class Node
Object data;
Node left;
Node right;
data = d;
class BinaryTree
Object tree[];
int maxSize;
maxSize = n;
tree[i] = a[i];
}
Node p = null;
p = new Node(tree[index]);
p.left = buildTree(2*index+1);
p.right = buildTree(2*index+2);
return p;
if( p != null )
inorder(p.left);
inorder(p.right);
if( p != null )
preorder(p.left);
preorder(p.right);
}
if( p != null )
postorder(p.left);
postorder(p.right);
if(p == null )
System.out.println("Tree is empty");
return;
stk.push(p);
while( !stk.isEmpty() )
p = stk.pop();
if( p != null )
stk.push(p.right);
stk.push(p.left);
}
public void inorderIterative(Node p)
if(p == null )
System.out.println("Tree is empty");
return;
if( p != null )
p = p.left;
else
if(p == null )
System.out.println("Tree is empty");
return;
Node tmp = p;
while( p != null )
{
stk.push(p);
p = p.left;
tmp = p;
if( stk.isEmpty() )
return;
p = stk.pop();
stk.push(p);
p = p.right;
class BinaryTreeDemo
Object arr[] = {'E', 'C', 'G', 'A', 'D', 'F', 'H', null,'B',
null, null, null, null, null, null, null, null, null, null };
t.inorder(root);
System.out.print("\n preorder: ");
t.preorder(root);
t.postorder(root);
t.inorderIterative(root);
t.preorderIterative(root);
t.postorderIterative(root);
OUTPUT:
Laboratory Record Experiment No:__________________
14.Write Java programs for the implementation of bfs and dfs for a given graph.
//bfs
import java.io.*;
class quelist
maxsize = size;
for(int i = front;i<=rear;i++)
System.out.print(que[i]+" ");
if(front==-1)
front = 0;
que[++rear]=x;
return temp;
return((front>rear)||(front==-1));
class vertex
label = lab;
wasvisited = false;
}
class graph
quelist qu;
public graph()
nverts = 0;
qu = new quelist(MAX);
for(int i=0;i<MAX;i++)
for(int j=0;j<MAX;j++)
adj[i][j] = 0;
adj[start][end] = 1;
adj[end][start] = 1;
{
for(int j=0;j<nverts;j++)
if((adj[i][j]==1)&&(vlist[j].wasvisited==false))
return j;
return (MAX+1);
System.out.print(vlist[i].label);
for(int i=0;i<nverts;i++)
if(vlist[i].label==l)
return i;
return (MAX+1);
vlist[0].wasvisited = true;
display(0);
qu.enque(0);
int v2;
while(!(qu.isempty()))
int v1 = qu.deque();
while((v2=getadjunvis(v1))!=(MAX+1))
vlist[v2].wasvisited = true;
display(v2);
qu.enque(v2);
System.out.print("\n");
class bfs
int n = Integer.parseInt(br.readLine());
for(int i=0;i<n;i++)
char ch = temp.charAt(0);
gr.addver(ch);
for(int j=0;j<edg;j++)
String t = br.readLine();
char c = t.charAt(0);
int start = gr.getind(c);
t = br.readLine();
c = t.charAt(0);
gr.addedge(start,end);
gr.brfs();
OUTPUT:
//dfs
import java.io.*;
import java.util.*;
class Stack
int top;
Stack()
top=-1;
if (top==9)
System.out.println("Stack overflow");
else
stk[++top]=item;
}/*end push*/
boolean isempty()
if (top<0)
return true;
else
return false;
}/*end isempty*/
int pop()
if (isempty())
{
System.out.println("Stack underflow");
return 0;
else
return (stk[top--]);
}/*end pop*/
void stacktop()
if(isempty())
else
}/*end stacktop*/
void display()
System.out.println("Stack-->");
for(int i=0;i<=top;i++)
System.out.println(stk[i]);
}/*end display*/
class Graph
int MAXSIZE=51;
int n,i,j,parent,adj_parent,initial_node;
int ans=0,ans1=0;
n=getNumber();
for ( i=1;i<=n;i++)
for( j=1;j<=n;j++)
adj[i][j]=0;
/*All graph nodes are unvisited, hence assigned zero to visited field of each node */
visited[c]=0;
do
parent=getNumber();
do
adj_parent=getNumber();
adj[parent][adj_parent]=1;
adj[adj_parent][parent]=1;
ans1= getNumber();
} while (ans1==1);
System.out.print("\nContinue to add graph node?");
ans= getNumber();
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
System.out.print(" "+adj[i][j]);
System.out.print("\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
if (adj[i][j]==1)
System.out.print(" "+j);
initial_node=getNumber();
int u,i;
s.top = -1;
s.push(initial_node);
while(!s.isempty())
u=s.pop();
if(visited[u]==0)
System.out.print("\n"+u);
visited[u]=1;
for (i=1;i<=n;i++)
s.push(u);
visited[i]=1;
System.out.print(" "+i);
u = i;
int getNumber()
String str;
int ne=0;
str=in.readLine();
ne=Integer.parseInt(str);
catch(Exception e)
System.out.println("I/O Error");
return ne;
class Graph_DFS
g.createGraph();
} /* end of program */
}
OUTPUT:
Laboratory Record Experiment No:__________________
15. Write Java programs for implementing the following sorting methods:
//Bubble Sort
import java.io.*;
class BubbleSort
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
display( arr );
bubbleSort( arr );
display( arr );
int tmp;
exch = 0;
tmp = a[i];
a[i] = a[i+1];
a[i+1] = tmp;
exch++;
}
OUTPUT:
//Insertion Sort
import java.io.*;
class InsertionSort
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
display( arr );
insertionSort( arr );
display( arr );
int i, j, n = a.length;
int item;
item = a[j];
i = j-1;
a[i+1] = a[i];
i = i-1;
a[i+1] = item;
OUTPUT:
//Quick Sort
import java.io.*;
class QuickSort
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
display( arr );
display( arr );
newleft++;
newright--;
tmp = a[newleft];
a[newleft] = a[newright];
a[newright] = tmp;
newleft++; newright--;
}
OUTPUT:
//Merge Sort
import java.io.*;
class MergeSort
int[] a;
int[] tmp;
MergeSort(int[] arr)
a = arr;
InputStreamReader(System.in));
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
display( arr );
ms.msort();
System.out.print("\n Sorted array: ");
display( arr );
void msort()
sort(0, a.length-1);
sort(left, mid);
sort(mid+1, right);
int i = left;
int j = left;
int k = mid+1;
tmp[i++] = a[j++];
else
tmp[i++] = a[k++];
a[i] = tmp[i];
OUTPUT:
//Heap Sort
import java.io.*;
class HeapSort
int[] a;
int maxSize;
int currentSize;
public HeapSort(int m)
maxSize = m;
currentSize = 0;
a = new int[maxSize];
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
display( arr );
HeapSort hs=new HeapSort(n);
hs.heapsort(arr);
display( arr );
if(currentSize == maxSize)
return false;
a[currentSize] = key;
moveUp(currentSize++);
return true;
a[index] = a[parent];
index = parent;
parent = (parent-1)/2;
a[index] = bottom;
if( isEmpty() )
{
System.out.println("Heap is empty");
return -1;
a[0] = a[--currentSize];
moveDown(0);
return root;
int largerChild;
largerChild = rightChild;
else
largerChild = leftChild;
a[index] = a[largerChild];
index = largerChild;
a[index] = top;
return currentSize==0;
h.insert(arr[i]);
arr[i] = h.remove();
OUTPUT:
//Radix Sort
import java.io.*;
class RadixSort
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
int n1=Integer.parseInt(br1.readLine());
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
display( arr );
radixSort(arr,n,n1);
display( arr );
int d, j, k, m, divisor;
divisor = 1;
m = (arr[j]/divisor) % radix;
queue[m].addLast(new Integer(arr[j]));
divisor = divisor*radix;
while( !queue[j].isEmpty())
arr[k++] = (Integer)queue[j].removeFirst();
}
OUTPUT:
//Binary Tree Sort
import java.io.*;
class BSTNode
int data;
BSTNode left;
BSTNode right;
data = d;
class BinarySearchTree
int i;
int[] a;
BSTNode root;
a = new int[arr.length];
a = arr;
if( p == null )
p = new BSTNode(key);
return p;
buildTree();
i = 0;
inorder(root);
if( p != null )
inorder(p.left);
a[i++] = p.data;
inorder(p.right);
}
class TreeSortDemo
//int arr[] = { 55, 22, 99, 77, 11, 88, 44, 66, 33 };
System.out.println("enter n value");
int n=Integer.parseInt(br.readLine());
System.out.println("enter elements");
for(int i=0;i<n;i++)
arr[i]=Integer.parseInt(br.readLine());
bst.display( arr );
bst.treeSort();
bst.display( arr );
}
OUTPUT:
Laboratory Record Experiment No:__________________
class BTree
int count;
int m;
/*
* No node has key equal to new key (duplicate keys are not allowed.
*/
boolean pushup;
if ( pushup )
node.count = 1;
node.key[1] = i.m;
node.child[0] = root;
node.child[1] = c;
root = node;
/*
*/
if ( node == null )
p.m = val;
c = null;
return true;
else
return false;
else
return true;
return false;
/*
*/
if ( root == null )
return null ;
else
return root;
else
/*
*/
pos.m = 0 ;
return false ;
else
pos.m = node.count ;
(pos.m)--;
if ( val == node.key[pos.m] )
return true;
else
return false;
/*
*/
{
int i ;
node.key[i + 1] = node.key[i];
node.child[i + 1] = node.child[i];
node.key[k + 1] = val ;
node.child[k + 1] = c ;
node.count++ ;
/*
* Splits a full node into current node and new right child
* with median.
*/
void split( int val, BTNode c, BTNode node,int k, Ref y, BTNode newnode )
if ( k <= MIN )
mid = MIN;
else
mid = MIN + 1;
newnode.key[i-mid] = node.key[i];
newnode.child[i-mid] = node.child[i];
node.count = mid;
if ( k <= MIN )
y.m = node.key[node.count];
newnode.child[0] = node.child[node.count] ;
node.count-- ;
// calls display( )
void displayTree()
display( root );
int i;
if ( root != null )
display( root.child[i] );
display( root.child[i] );
class BTreeDemo
{
BTree bt = new BTree();
int[] arr = { 11, 23, 21, 12, 31, 18, 25, 35, 29, 20, 45,
bt.insertTree( arr[i] );
bt.displayTree();
OUTPUT:
Laboratory Record Experiment No:__________________
17. Write a Java program that implements Kruskals algorithm to generate minimum cost spanning tree.
import java.io.*;
import java.util.*;
class Graph
int cost=0;
int getNumber()
String str;
int ne=0;
try
str=in.readLine();
ne=Integer.parseInt(str);
}
catch(Exception e)
System.out.println("I/O Error");
return ne;
}/*end getNumber*/
void read_graph()
graph ::");
n=getNumber();
noe=0;
for(int i=1;i<=n;i++)
for(int j=i+1;j<=n;j++)
int w;
w=getNumber();
if(w!=0)
noe++;
graph_edge[noe][1]=i;
graph_edge[noe][2]=j;
graph_edge[noe][3]=w;
}
}
void sort_edges()
for(int i=1;i<=noe-1;i++)
for(int j=1;j<=noe-i;j++)
if(graph_edge[j][3]>graph_edge[j+1][3])
int t=graph_edge[j][1];
graph_edge[j][1]=graph_edge[j+1][1];
graph_edge[j+1][1]=t;
t=graph_edge[j][2];
graph_edge[j][2]=graph_edge[j+1][2];
graph_edge[j+1][2]=t;
t=graph_edge[j][3];
graph_edge[j][3]=graph_edge[j+1][3];
graph_edge[j+1][3]=t;
void algorithm()
for(int i=1;i<=n;i++)
{
sets[i][1]=i;
top[i]=1;
for(i=1;i<=noe;i++)
int p1=find_node(graph_edge[i][1]);
int p2=find_node(graph_edge[i][2]);
if(p1!=p2)
cost=cost+graph_edge[i][3];
tree[graph_edge[i][1]][graph_edge[i][2]]=graph_edge[i][3];
tree[graph_edge[i][2]][graph_edge[i][1]]=graph_edge[i][3];
for(int j=1;j<=top[p2];j++)
top[p1]++;
sets[p1][top[p1]]=sets[p2][j];
top[p2]=0;
else
{
so it is removed\n\n");
int find_node(int n)
for(int i=1;i<=noe;i++)
for(int j=1;j<=top[i];j++)
if(n==sets[i][j])
return i;
return -1;
class Kruskal1
obj.read_graph();
obj.sort_edges();
obj.algorithm();
OUTPUT:
Laboratory Record Experiment No:__________________
18. Write a Java program that implements KMP algorithm for pattern matching.
//KMPDemo.java
import java.io.*;
class KMPDemo
InputStreamReader(System.in));
String T = br.readLine();
InputStreamReader(System.in));
String P = br1.readLine();
if(isMatch)
else
}
static boolean kmp(String T, String P)
int n = T.length();
int m = P.length();
while( i < n )
if( j == m-1 )
return true;
i++;
j++;
j = fail[j-1];
else i++;
return false;
int m = P.length();
fail[0] = 0;
int i = 1;
int j = 0;
while( i < m )
{
if( P.charAt(j) == P.charAt(i) ) // j+1 characters match
fail[i] = j+1;
i++;
j++;
j = fail[j-1];
else // no match
fail[i] = 0;
i++;
return fail;
OUTPUT: