Вы находитесь на странице: 1из 54

Ex.

No:1

IMPLEMENTATION OF MINHEAP

DATE:

AIM
To write a java program to implement MinHeap

ALGORITHM
STEP1- Start the program.

STEP2- Create an empty heap and enter the size of the heap

STEP3- Insertion of a new element into the heap

STEP4- Add the element to the bottom level of the heap.


STEP5- Compare the added element with its parent; if they are in the correct order,
Stop the process.
STEP6- If not, swap the element with its parent and return to the previous step.
STEP7- Deletion of the smallest element from the heap

STEP8- Replace the root of the heap with the last element on the last level.
STEP9- Compare the new root with its children; if they are in the correct order, stop.
STEP10- If not, swap the element with one of its children and return to the previous
step. (Swap with its smaller child in a min-heap and its larger child in a
1

max- heap.)

PROGRAM
import java.io.*;
public class MinHeap
{
private int[] Heap;
private int maxsize;
private int size;
public MinHeap(int max)
{
maxsize = max;
Heap = new int[maxsize];
size = 0 ;
Heap[0] = Integer.MIN_VALUE;
}
private int leftchild(int pos)
{
return 2*pos;
}
private int rightchild(int pos)
{
return 2*pos + 1;
}
private int parent(int pos)
{
return pos / 2;
}
private boolean isleaf(int pos)
{
return ((pos > size/2) && (pos <= size));
}
private void swap(int pos1, int pos2)
{
int tmp;
2

tmp = Heap[pos1];
Heap[pos1] = Heap[pos2];
Heap[pos2] = tmp;
}
public void insert(int elem)
{
size++;
Heap[size] = elem;
int current = size;
while (Heap[current] < Heap[parent(current)])
{
swap(current, parent(current));
current = parent(current);
}
}
public void print()
{
int i;
for (i=1; i<=size;i++)
System.out.print(Heap[i] + " ");
System.out.println();
}
public int removemin()
{
swap(1,size);
size--;
if (size != 0)
pushdown(1);
return Heap[size+1];
}
private void pushdown(int position)
{
int smallestchild;
while (!isleaf(position))
{
smallestchild = leftchild(position);
if ((smallestchild < size) && (Heap[smallestchild] > Heap[smallestchild+1]))
smallestchild = smallestchild + 1;
if (Heap[position] <= Heap[smallestchild]) return;
swap(position,smallestchild);
position = smallestchild;
}
}
public static void main(String[] args)
{
InputStreamReader xx = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(xx) ;
try
3

{
MinHeap m=new MinHeap(50);
int ans=1;
while(ans==1)
{
System.out.println("1.INSERT ");
System.out.println("2.REMOVE ");
System.out.println("3.Exit ");
System.out.println("\n");
System.out.println("Enter ur choice:");
System.out.println("\n");
String ch=bufRead.readLine();
int chh = Integer.parseInt(ch);
switch(chh)
{
case 1:
System.out.println("1.ENTER THE SIZE ");
String ms=bufRead.readLine();
int mss = Integer.parseInt(ms);
System.out.println("1.ENTER THE VALUE TO INSERT ");
for(int i=0;i<mss;i++)
{
String ins=bufRead.readLine();
int inss = Integer.parseInt(ins);
m.insert(inss);
}
System.out.println("THE VALUES ARE INSERTED
SUCCESSFULLY");
m.print();
System.out.println("\n");
break;
case 2:
int rem;
rem=m.removemin() ;
System.out.println("\n");
System.out.println("the min val"+"("+rem+")"+"is deleted successfully");
System.out.println("\n");
m.print();
System.out.println("\n");
break;
case 3:
System.out.println("Exit");
System.exit(0);
default:
System.out.println("Enter the valid choice");
}
}
}
catch(IOException err)
4

{
System.out.println(err);
}
}
}

OUTPUT

RESULT
Thus the java program to implement minheap has been executed and output is verified
successfully.

Ex.No: 2

IMPLEMENTATION OF DEAPS

DATE:

AIM
To write a java program to implement deaps.

ALGORITHM
INSERTION:
STEP 1 - Get the number of elements for deap.
STEP 2 - Set the root in such a way that it contains no element.
STEP 3 - The elements in the left sub tree is a min-heap. Place the min element
in the root of the min-heap.
STEP 4 - The elements in the right sub tree is a max-heap. Place the max element
in the root of the max-heap.
STEP 5- If the right sub tree is not empty, then let i be any node in the left sub
tree.
STEP 6- Let j be the corresponding node in the right sub tree. If such a j does
not exist, then
let j be the node in the right sub tree that corresponds to the parent of
i.The key in node i is less than or equal to the key in j.
6

STEP 7- Insert the element in such a way that the deap property is not violated.
DELETION:
STEP 1-Place the last element into a temporary element c.
STEP 2 -Vacancy created by the deletion of the min element is filled by moving from
position 2 to a leaf.
STEP 3-Each move is preceded by a step that moves the smaller of the element in the
children of the current node up.
STEP 4 -Then move to the position previously occupied by the moved element.
STEP 5- Repeat the process until we move the empty node to a leaf position
STEP 6 -Compare the key put in the temporary element with max partner
a. If lesser, no exchange is needed. The temporary element is inserted into the
empty leaf node
b. If greater, exchange them

PROGRAM
import java.io.*;
import java.util.*;
public class deaps
{
int[] deap;
int n = 1;
public deaps(int maxSize)
{
deap = new int[maxSize];
}
private boolean inMaxHeap(int i)
{
while (i > 3)
{
i /= 2;
}
if (i == 2)
return false;
return true;
}
private int maxPartner(int pos)
{
int offset = 1;
int i = pos;
while (i > 3)
7

{
i /= 2;
offset *= 2;
}
if ((pos + offset) > n)
return (pos+offset)/2;
return pos + offset;
}
private int minPartner(int pos)
{
int offset = 1;
int i = pos;
while (i > 3)
{
i /= 2;
offset *= 2;
}
return pos - offset;
}
private void minInsert(int at, int key)
{
for (int parent; (parent = at / 2) != 1 && key < deap[parent]; deap[at] = deap[parent], at =
parent) ;
deap[at] = key;
}
private void maxInsert(int at, int key)
{
for (int parent; (parent = at / 2) != 1 && key > deap[parent]; deap[at] = deap[parent], at =
parent) ;
deap[at] = key;
}
public int deleteMax()
{
int i, j;
int key;
if (n >= 3)
{ // if more than 2 elements
key = deap[3];
}
else
{
n--;
return deap[2];
}
int x = deap[n--];
// while i has child, move larger to i
for (i = 3; 2*i <= n; deap[i] = deap[j], i = j)
{
8

j = i * 2;
if (j+1 <= n)
{
if (deap[j] < deap[j+1])
{
j++;
}
}
}
j = minPartner(i);
int biggest = j;
if (2*j <= n)
{
biggest = 2*j;
if (((2*j + 1) <= n) && (deap[2*j] < deap[2*j+1]))
{
biggest++;
}
}
if (x < deap[biggest])
{
deap[i] = deap[biggest];
minInsert(biggest, x);
}
else
{
maxInsert(i, x);
}
return key;
}
public int deleteMin()
{
int i, j, key = deap[2], x = deap[n--];
// while i has child, move smaller to i
for (i = 2; 2*i <= n; deap[i] = deap[j], i = j)
{
j = i * 2;
if (j+1 <= n && deap[j] > deap[j+1])
{
j++;
}
}
j = maxPartner(i);
if (x > deap[j])
{
deap[i] = deap[j];
maxInsert(j, x);
}
9

else
{
minInsert(i, x);
}
return key;
}
public void insert(int x)
{
n++;
if (n == deap.length)
{
System.out.println("The heap is full");
System.exit(1);
}
if (n == 2)
{
deap[2] = x;
return;
}
if (inMaxHeap(n))
{
int i = minPartner(n);
if (x < deap[i])
{
deap[n] = deap[i];
minInsert(i, x);
}
else
{
maxInsert(n, x);
}
}
else
{
int i = maxPartner(n);
if (x > deap[i])
{
deap[n] = deap[i];
maxInsert(i, x);
}
else
{
minInsert(n, x);
}
}
}
public void print()
{
10

int levelNum = 2;
int thisLevel = 0;
int gap = 8;
for (int i = 2; i <= n; i++)
{
for (int j = 0; j < gap-1; j++)
{
System.out.print(" ");
}
if (thisLevel != 0)
{
for (int j = 0; j < gap-1; j++)
{
System.out.print(" ");
}
}
if (Integer.toString(deap[i]).length() == 1)
{
System.out.print(" ");
}
System.out.print(deap[i]);
thisLevel++;
if (thisLevel == levelNum)
{
System.out.println();
thisLevel = 0;
levelNum *= 2;
gap/=2;
}
}
System.out.println();
if (thisLevel != 0)
{
System.out.println();
}
}
public static void main(String[] argv)throws IOException
{
System.out.println("enter the no of nodes");
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
deaps a = new deaps(1024);
int n,j=0,x;
String s,si,s1;
s=r.readLine();
n=Integer.parseInt(s);
System.out.println("enter the elements");
for (int i = 0; i < n;i++)
{
11

si=r.readLine();
j=Integer.parseInt(si);
a.insert(j);
}
System.out.println("initial");
a.print();
System.out.println("Enter the element to be inserted");
s1=r.readLine();
x=Integer.parseInt(s1);
a.insert(x);
a.print();
System.out.println("delete Min");
a.deleteMin();
a.print();
System.out.println("delete Max");
a.deleteMax();
a.print();
}
}

OUTPUT

12

RESULT
Thus the java program to implement deaps has been executed and output is
verified successfully.

Ex.No: 3

IMPLEMENTATION OF LEFTIST HEAP

DATE:
13

AIM
To write a java program to implement leftist heap.

ALGORITHM
INSERTION
STEP1- To insert an element x into a min leftist tree, first create a min leftist tree that
contains the single element x. Then combine two min leftist trees.

DELETEMIN

STEP2- To delete the min element from a nonempty min leftist tree, combine the min
leftist trees root->LeftChild and root->RightChild and delete the node root.

COMBINE

STEP3- For a min - leftist tree, set the higher valued node as its right child of the
lower valued node.

STEP4- If the lower valued node already has a right child, then merge the higher
valued node with the sub-tree rooted by the right child of the lower node.

STEP5- After merging, the shortest-value of the lower valued node must be updated .

14

STEP6- Now check if the lower valued node has a left child. If it does not, then move
the right child to the left.

STEP7- If it does have a left child, then the child with the highest shortest-value
should go on the left.

PROGRAM
import java.io.*;
class IO
{
static int readInt()
{
String input="";
try
{
input=(new BufferedReader(new InputStreamReader(System.in))).readLine();
}
catch(java.io.IOException e)
{
System.out.println("Error while Reading");
}
return Integer.valueOf(input).intValue();
}}
class node
{
int key;
int npl;
node right;
node left;
public node(int key,node left,node right)
{
this.key=key;
this.right=right;
this.left=left;
15

}
public node(int key)
{
this(key,null,null);
}
static node merge(node u,node v)
{
if(u.key>v.key)
{
node dummy=u;
u=v;
v=dummy;
}
if(u.right==null)
u.right=v;
else
u.right=merge(u.right,v);
if(u.left==null||u.right.npl>u.left.npl)
{
node dummy=u.right;
u.right=u.left;
u.left=dummy;
}
if(u.right==null)
u.npl=0;
else
u.npl=min(u.left.npl,u.right.npl)+1;
return u;
}
static int min(int x,int y)
{
if(x<=y)
return x;
return y;
}
void print(int d)
{
System.out.println("Depth=="+d+",key=="+key);
if(left!=null)
{
System.out.print("Left");
left.print(d+1);
}
if(right!=null)
{
System.out.print("Right");
right.print(d+1);
} } }
class leftistheap
16

{
node root;
public leftistheap()
{
root=null;
}
public void insert(int key)
{
if(root==null)
root=new node(key);
else
root=node.merge(root,new node(key));
}
public int deletemin()
{
if(root==null)
{
System.out.println("Empty Heap");
return Integer.MAX_VALUE;
}
else
{
int x=root.key;
if(root.right==null)
root=root.left;
else
root=node.merge(root.left,root.right);
return x;
}
}
void print()
{
if(root==null)
System.out.println("\n Empty Tree");
else
{
System.out.println("\n Printing All node");
System.out.println("Root");
root.print(0);
}
System.out.println();
}
}
public class leftist
{
public static void main(String[] args)
{
System.out.println();
leftistheap heap=new leftistheap();
17

System.out.println("Step by step test? yes=1");


if(IO.readInt()==1)
{
int c=0;
while(c<4)
{
System.out.println("Leftist Tree operation:");
System.out.println("1.Insert,2.Delete,3.Print,4.Exit:");
c=IO.readInt();
if(c==1)
{
System.out.println("Give key to insert:");
heap.insert(IO.readInt());
}
else if(c==2)
System.out.println("Delete Min returns"+heap.deletemin());else if(c==3)
heap.print();
}
}
}
}

OUTPUT

18

RESULT
Thus the java program to implement leftist heap has been executed and output is verified
successfully.

Ex.No:4
DATE:

IMPLEMENTATION OF AVL TREE

AIM
To write a java program to implement insertion in AVL Tree.

ALGORITHM
STEP1- Start the program by defining the functions.
STEP2- Insert the elements to the AVL tree.
STEP3- Check the tree if it is balanced or not.
STEP4- The balance factor is one of 0, 1 and -1.
STEP5- If it is not balanced, balance the tree using rotations.
i)Left-Left
ii)Left-Right
19

iii)Right-Left
iv)Right-Right
STEP6- And if the tree is balanced and then the insert() operations is
performed.
STEP7- Stop the program

PROGRAM
import java.io.*;
class avlnode
{
int data,bf;
public avlnode lchild,rchild,parent;
}
class avl
{
avlnode root=null;
avlnode p=null;
avlnode prev=null;
public void insert(int ele)
{
avlnode temp=new avlnode();
temp.data=ele;
temp.lchild=null;
temp.rchild=null;
temp.parent=null;
p=new avlnode();
p=root;
if(root==null)
root=temp;
else
20

{
while(p!=null)
{
prev=p;
if(p.data>temp.data)
p=p.lchild;
else
p=p.rchild;
}
if(prev.data>temp.data)
{
prev.lchild=temp;
prev.lchild.parent=prev;
prev.bf+=1;
}
else
{
prev.rchild=temp;
prev.rchild.parent=prev;
prev.bf-=1;
}
while((prev!=null) && prev.bf!=2 && prev.bf!=-2)
{
p=prev;
prev=prev.parent;
if(prev!=null)
{
if(p==p.lchild)
prev.bf+=1;
else
prev.bf-=1;
}
}
System.out.println("Tree Before Rotation");
dispre(root);
if(prev!=null && prev.bf==2)
{
switch(p.bf)
{
case 1:
System.out.println("LL Rotation");
ll_rotate();
dispre(root);
break;
case -1:
System.out.println("LR Rotate");
lr_rotate();
dispre(root);
break;
21

}
}
if(prev!=null && prev.bf==-2)
{
switch(p.bf)
{
case 1:
System.out.println("RL Rotation");
rl_rotate();
dispre(root);
break;
case -1:
System.out.println("RR Rotate");
rr_rotate();
dispre(root);
break;
}}}}
public void ll_rotate()
{
p.parent=prev.parent;
if(prev.parent!=null)
prev.parent.lchild=p;
p.rchild=prev;
prev.lchild=null;
if(prev==root)
root=p;
prev.bf=0;
p.bf=0;
}
public void rr_rotate()
{
p.parent=prev.parent;
if(prev.parent!=null)
prev.parent.rchild=p;
p.lchild=prev;
prev.rchild=null;
if(prev==root)
root=p;
prev.bf=0;
p.bf=0;
}
public void lr_rotate()
{
avlnode t=p.rchild;
if(t.lchild!=null)
p.rchild=t.lchild;
else
p.rchild=null;
if(t.rchild!=null)
22

prev.lchild=t.rchild;
else
prev.lchild=null;
if(prev.parent!=null)
{
t.parent=prev.parent;
prev.parent.lchild=t;
}
else
{
t.parent=null;
root=t;
}
t.rchild=prev;
t.lchild=p;
p.bf=0;
prev.bf=0;
t.bf=0;
}
public void rl_rotate()
{
avlnode t=p.lchild;
if(t.rchild!=null)
p.lchild=t.rchild;
else
p.lchild=null;
if(t.lchild!=null)
prev.rchild=t.lchild;
else
prev.rchild=null;
if(prev.parent!=null)
{
t.parent=prev.parent;
prev.parent.rchild=t;
}
else{
t.parent=null;
root=t;
}
t.lchild=prev;
t.rchild=p;
p.bf=0;
prev.bf=0;
t.bf=0;
}
public void dispre(avlnode cnode)
{
if(cnode!=null)
{
23

dispre(cnode.lchild);
System.out.println(cnode.data+"bf="+cnode.bf);
dispre(cnode.rchild);
}
}}
public class avltree
{
public static void main(String args[])throws IOException
{
int cho,ele;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
avl tree=new avl();
System.out.println("1.Insert,2.Exit");
while(true)
{
System.out.println("Enter the choice");
cho=Integer.parseInt(br.readLine());
switch(cho)
{
case 1:
System.out.println("Enter data");
ele=Integer.parseInt(br.readLine());
tree.insert(ele);
break;
case 2:
System.exit(0);
}}}}

OUTPUT

24

RESULT
Thus the java program to implement avl tree has been executed and output is
verified successfully.

Ex.No:5

IMPLEMENTATION OF B-TREE

DATE:

AIM
To write a java program to implement the B-Tree.

ALGORITHM
STEP1- Start the program by defining function.
STEP2- Declare the class btree

25

STEP3- To insert, check if root is empty, if it is empty insert the element as root.
STEP4- If it is greater insert it into right sub tree. Otherwise, insert it into left sub tree
STEP5- Use the function split, to split the nodes
STEP6- Call the function display to display data1,data2, and parent
STEP7- End of the program

PROGRAM
import java.io.*;
class bnode
{
int data1,data2;
bnode lptr,mptr,rptr,parent;
public void bnode()
{
this.data1=this.data2=0;
this.lptr=this.mptr=this.rptr=this.parent=null;
}
}
class btree
{
bnode root=null;
bnode p,p1;
bnode prev;
void insert(int ele)
26

{
bnode temp=new bnode();
temp.data1=ele;
if(root==null)
{
root=temp;
}
else
{
p1=root;
while(p1!=null)
{
prev=p1;
if(temp.data1<p1.data1)
p1=p1.lptr;
else if((temp.data1>p1.data1) &&(temp.data1<p1.data2))
p1=p1.mptr;
else
p1=p1.rptr;
}
p1=prev;
while(p1!=null)
{
if(p1.data2==0)
{
if(temp.data1<p1.data1)
{
int t=p1.data1;
p1.data1=temp.data1;
p1.data2=t;
p1.lptr=temp.lptr;
if(temp.lptr!=null)
temp.lptr.parent=p1;
p1.mptr=temp.rptr;
if(temp.rptr!=null)
temp.rptr.parent=p1;
}
else
{
p1.data2=temp.data1;
p1.mptr=temp.lptr;
if(temp.lptr!=null)
temp.lptr.parent=p1;
p1.rptr=temp.rptr;
if(temp.rptr!=null)
temp.rptr.parent=p1;
temp.parent=p1.parent;
}
27

temp.parent=p1.parent;
break;
}
else if((p1.data1!=0) && (p1.data2!=0))
{
p1=split(temp,p1);
temp=p1;
p1=p1.parent;
}
}
}
display(root);
}
bnode split(bnode t,bnode p)
{
bnode n1=null;
bnode n2=null;
if(t.data1<p.data1)
{
if(p.mptr!=null)
n1=p.mptr;
if(p.rptr!=null)
n2=p.rptr;
p.lptr=new bnode();
p.lptr=t;
t.parent=p;
p.mptr=null;
p.rptr=new bnode();
p.rptr.data1=p.data2;
p.rptr.lptr=n1;
if(n1!=null)
p.rptr.lptr.parent=p.rptr;
p.rptr.rptr=n2;
if(n2!=null)
p.rptr.rptr.parent=p.rptr;
p.rptr.parent=p;
p.data2=0;
}
else if((t.data1>p.data1) && (t.data1<p.data2))
{
if(p.lptr!=null)
n1=p.lptr;
if(p.rptr!=null)
n2=p.rptr;
p.lptr=new bnode();
p.lptr.data1=p.data1;
p.lptr.parent=p;
p.data1=t.data1;
28

p.lptr.lptr=n1;
if(n1!=null)
p.lptr.lptr.parent=p.lptr;
p.lptr.rptr=t.lptr;
if(t.lptr!=null)
p.lptr.rptr.parent=p.lptr;
p.rptr=new bnode();
p.rptr.data1=p.data2;
p.rptr.rptr=n2;
if(n2!=null)
p.rptr.rptr.parent=p.rptr;
p.rptr.lptr=t.rptr;
if(t.rptr!=null)
p.rptr.lptr.parent=p.rptr;
p.rptr.parent=p;
p.data2=0;
p.mptr=null;
}
else
{
if(p.lptr!=null)
n1=p.lptr;
if(p.mptr!=null)
n2=p.mptr;
p.lptr=new bnode();
p.lptr.data1=p.data1;
p.lptr.parent=p;
p.mptr=null;
p.lptr.lptr=n1;
if(n1!=null)
p.lptr.lptr.parent=p.lptr;
p.lptr.rptr=n2;
if(n2!=null)
p.lptr.rptr.parent=p.lptr;
p.data1=p.data2;
p.data2=0;
p.rptr=new bnode();
p.rptr=t;
p.rptr.parent=p;
}
return p;
}
void display(bnode temp)
{
if(temp!=null)
{
display(temp.lptr);
display(temp.mptr);
29

display(temp.rptr);
System.out.println("data1::"+temp.data1+" data2::"+temp.
data2+" Address::"+temp+" parent::"+temp.parent);
}
}
}
class btrees
{
public static void main(String[] args)throws IOException
{
System.out.println("B-Trees");
DataInputStream in=new DataInputStream(System.in);
btree bt=new btree();
int x,ch;
do
{
System.out.println("Enter the element");
x=Integer.parseInt(in.readLine());
bt.insert(x);
System.out.println("To continue...press 1");
ch=Integer.parseInt(in.readLine());
}while(ch==1);
}
}

OUTPUT

30

RESULT
Thus the java program to implement b-tree has been executed and output is verified
successfully.

Ex.No: 6

IMPLEMENTATION OF TRIES

DATE:
31

AIM
To write a java program to implement the Tries.

ALGORITHM

STEP1- Start the program by defining the functions.


STEP2- First initialize the node to null.
STEP3- To find the particular element use function find check the element to root
node, if it is not found check for left or right side of the root. If its found
return the element .
STEP4- To insert the particular element read that elemnt and insert the element with
tag as 0 and level as 1.
STEP5- To display the elements, display if root as null, print as empty, otherwise call
empty .
STEP6- Print the current node in left sub tree in the format as current node.
STEP7- Display current node in the right sub tree.

PROGRAM
import java.io.*;
class node
32

{
public int tag,level;
public int data;
public node LC,RC,par;
}
class trie
{
public node cptr;
public node root=null;
public node find(int key)
{
int item=key;
node temp=root;
while(temp!=null)
{
cptr=temp;
if(temp.tag==1)
{
if((item & 1)==0)
{
temp=temp.LC;
item=item >> 1;
}
else
{
temp=temp.RC;
item=item >> 1;
}
}
else
{
if(key==temp.data)
{
return temp;
}
else break;
}
}
return null;
}
public void insert()
{
int key=0;
try
{
System.out.println("Enter the element:");
DataInputStream din=new DataInputStream(System.in);
key=Integer.parseInt(din.readLine());
33

}
catch(Exception e){}
if(root==null)
{
root=new node();
root.data=key;
root.tag=0;
root.level=1;
root.par=null; root.LC=null; root.RC=null;
}
else
{
node temp=find(key);
if(temp==null)
{
temp=cptr;
if(temp.tag==0)
{
node n1=new node();
node n2=new node();
temp.tag=1;
n1.tag=0;n2.tag=0;
int k1=temp.data;temp.data=0;
int k2=key;
int kk1;
n1.data=k1;
n2.data=k2;
int lv=1;
while ( (k1 & 1 ) ==(k2 & 1 ))
{
kk1=k1;
k1=k1 >> 1;
k2=k2 >> 1;
if(lv>=temp.level)
{
node n3=new node();
n3.tag=1;
if ( (kk1 & 1)==0)
{
temp.LC=n3;
temp.RC=null;
n3.level=temp.level+1;
}
else
{
temp.RC=n3;
temp.LC=null;
n3.level=temp.level+1;
34

}
n3.par=temp;
temp=n3;
lv++;
}
else
lv++;
}
if( (k1 & 1)==0)
{
temp.LC=n1;
temp.RC=n2;
n1.level=n2.level=temp.level+1;
}
else
{
temp.LC=n2;
temp.RC=n1;
n1.level=n2.level=temp.level+1;
n1.par=temp;
}
n2.par=temp;
}
else
{
node n1=new node();
n1.tag=0;
n1.data=key;
if(temp.LC==null)
temp.LC=n1;
else
temp.RC=n1;
n1.level=temp.level+1;
n1.par=temp;
}
}
else
System.out.println("Element already exists");
}
}
public void display()
{
if(root==null)
System.out.println("EMPTY");
else
{
System.out.println("\nIn Order");
dispin(root);
35

}
}
public void dispin(node currentnode)
{
if(currentnode!=null)
{
dispin(currentnode.LC);
System.out.println(currentnode.data+" "+"LEVEL"+currentnode.level+"
"+"TAG-"+currentnode.tag);
dispin(currentnode.RC);
}
}
};
class TrieImp
{
public static void main(String args[ ])throws IOException
{
int ch=0,cont=0;
trie t = new trie();
do
{
System.out.println("TRIES 1. Insert ");
DataInputStream din = new DataInputStream(System.in);
try
{
ch=Integer.parseInt(din.readLine());
}
catch(Exception e){}
if(ch==1)
{
t.insert();
t.display();
}
else
{
System.out.println("Enter the correct choice");
}
System.out.println("press 1 to continue:");
try
{
cont=Integer.parseInt(din.readLine());
}
catch(Exception e){}
}while(cont==1);
}
}

36

OUTPUT

RESULT
Thus the java program to implement trie has been executed and output is verified
successfully.

37

Ex.No: 7

IMPLEMENTATION OF QUICK SORT

DATE:

AIM
To write a java program to implement Quick sort.

ALGORITHM
STEP1- Start the Program
STEP2- Choose an array value (first) to use as the pivot

STEP3- Starting from the left end, find the first element that is greater than or equal to
the pivot

STEP4- Searching backward from the right end, find the first element that is less than
the pivot

STEP5- Interchange (swap) these two elements

STEP6- Repeat the steps until i<j.

STEP7- Stop the program.

38

PROGRAM
import java.io.*;
import java.lang.*;
class sort
{
int i,j,pivot;
void quick(int a[],int first,int last)
{
if(first<last)
{
pivot=a[first];
i=first;
j=last;
while(i<j)
{
while(a[i]<=pivot && i<last)
i++;
while(a[j]>=pivot && j>first)
j--;
if(i<j)
swap(a,i,j);
}
swap(a,first,j);
quick(a,first,j-1);
quick(a,j+1,last);
}
}
void swap(int a[],int i ,int j)
{
int temp;
temp=a[i];
39

a[i]=a[j];
a[j]=temp;
}
}
class qusort
{
public static void main(String args[])throws IOException
{
int i,n;
int array[]=new int[20];
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
sort s=new sort();
System.out.println("Enter the number of elements");
String s1=br.readLine();
n=Integer.parseInt(s1);
System.out.println("Enter the elements");
for(i=0;i<n; i++)
{
String s2=br.readLine();
array[i]=Integer.parseInt(s2);
}
System.out.println("Before soting elements");
for(i=0; i<n; i++)
System.out.println(array[i]);
s.quick(array,0,n-1);
System.out.println("After sorting elements");
for(i=0; i<n; i++)
System.out.println(array[i]);
}
}

40

OUTPUT

41

RESULT
Thus the java program to implement quick sort has been executed and output is verified
successfully.

Ex.No: 8

IMPLEMENTATION OF CONVEX HULL

DATE:

AIM
To write a java program to implement the convex hull

ALGORITHM
STEP1- Start the program
STEP2- Create a class convexhullalg
STEP3- Read the number of points
STEP4- Get the x and y co-ordinate values
STEP5- Sort the values using sort function
STEP6- To sort two values swap the values of i and j
STEP7- Call the function display to display the boundary points

42

STEP8- The function check id used to check whether the point is


angularornot(180)
STEP9- End of the program.

PROGRAM
import java.io.*;
class convexhullalg
{
int x[],y[],n;
boolean status[];
void insert()
{
try
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter number of points:");
n=Integer.parseInt(in.readLine());
x=new int[n];
y=new int[n];
status=new boolean[n];
System.out.println("Enter x and y coordinates for ");
for(int i=0;i<n;i++)
{
System.out.println("point "+(i+1));
x[i]=Integer.parseInt(in.readLine());
y[i]=Integer.parseInt(in.readLine());
status[i]=false;
} }
catch(Exception e){}
sort();
check(0,'L');
check(0,'H');
display();
}
43

void sort()
{
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
if((x[i]>x[j]) || ((x[i]==x[j]) && (y[i]>y[j])))
swap(i, j);
}
}
void swap(int i,int j)
{ int temp=x[i];
x[i]=x[j];
x[j]=temp;
temp=y[i];
y[i]=y[j];
y[j]=temp;
}
void display()
{
System.out.println("Boundary points are");
for(int i=0;i<n;i++)
if(status[i]==true)
System.out.println("("+x[i]+", "+y[i]+")");
}
void check(int p,char c)
{
double slope=0,degree=0,deg=0;
int next=0;
status[p]=true;
for(int i=p+1;i<n;i++)
{
try
{
slope=(double)(x[i]-x[p])/(double)(y[i]-y[p]);
degree=Math.toDegrees(Math.atan(slope));
if(degree < 0)
degree+=180;
}
catch(Exception e)
{
degree=90;
}
if(i==p+1)
{
deg=degree;
next=i;
}
else
{
44

if((c=='L' && deg>degree)||(c!='L' && deg<degree) ||(degree==deg && x[i]<x[next]))


{
deg=degree;
next=i;
}
}
}
if(next!=0)
check(next,c);
}}
class convexhull
{
public static void main(String arg[]) throws IOException
{
convexhullalg c=new convexhullalg();
c.insert()
}
}

OUTPUT

45

RESULT
Thus the java program to implement convex hull has been executed and output is
verified successfully.

Ex.No: 9

0/1 KNAPSACK USING DYNAMIC PROGRAMMING

DATE:

AIM
To write a java program to implement 0/1 knapsack using dynamic programming

ALGORITHM
STEP1- Start the program by defining functions.
STEP2- Initialize the weight and profit
STEP3- Read the number of objects that are given
STEP4- For each objects, print the profit and weight
STEP5- Initializing is set to false
STEP6- Display and print the item weight and profit
46

STEP7- Display the total cost


STEP8- Stop the program.

PROGRAM
import java.io.*;
class objects
{
int weight;
int profit;
}
public class knapsack
{
static int N,W;
static objects st[];
public static void main(String args[])throws IOException
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the number of objects:");
N=Integer.parseInt(in.readLine());
System.out.println("Enter the maximum weight sack can take:");
W=Integer.parseInt(in.readLine());
st=new objects[N+1];
st[0]=new objects();st[0].weight=st[0].profit=0;
for(int i=1;i<=N;i++)
{
st[i]=new objects();
System.out.println("\nFor object "+i);
System.out.print("Enter profit: ");
st[i].profit=Integer.parseInt(in.readLine());
System.out.print("Enter Weight: ");
st[i].weight=Integer.parseInt(in.readLine());
47

}
int [][] opt=new int[N+1][W+1];
boolean [][] sol= new boolean[N+1][W+1];
for(int n=1;n<=N;n++)
for(int w=1;w<=W;w++)
{
int option1=opt[n-1][w];
int option2=-1;
if(st[n].weight<=w)
option2=st[n].profit+opt[n-1][w-st[n].weight];
opt[n][w]=Math.max(option1, option2);
sol[n][w]=(option2 > option1);
}
boolean take[]=new boolean[N+1];
int prof=0;
for(int n=N,w=W;n>0;n--)
if(sol[n][w])
{
take[n]=true;
w=w-st[n].weight;
prof+=st[n].profit;
}
else
take[n]=false;
System.out.println("\nThe optimal solution is:");
System.out.println("Item \t weight \t profit");
for(int n=1;n<=N;n++)
if(take[n])
System.out.println(n+" \t "+st[n].weight+" \t\t "+st[n].profit);
System.out.println("\n Total profit:"+prof);
}
}

48

OUTPUT

49

RESULT
Thus the java program to implement 0/1 Knapsack programming has been
executed and output is verified successfully.

Ex.No : 10

GRAPH COLORING USING BACKTRACKING

DATE:

AIM
To write a java program to implement graph coloring using backtracking.

ALGORITHM
STEP1- Start the program and define the function.
STEP2- Create a class coloring
STEP3- Get the number of vertices in the graph
STEP4- Enter one if there is an edge in the graph

50

STEP5- And enter zero if there is no edge in the graph.


STEP6- Get the adjacency matrix of the given values.
STEP7- Perform all possible combinations that are given.
STEP8- Display all the combination.
STEP9- Display all the combination.

PROGRAM
import java.io.*;
class gcoloring
{
int a[][]=new int[10][10];
int x[]=new int[10];
int m, n;
void read()
{
DataInputStream in=new DataInputStream(System.in);
try
{
System.out.println("Enter number of vertices in the graph");
n=Integer.parseInt(in.readLine());
System.out.println("Enter 1 if there is an edge Otherwise 0");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
System.out.println("between "+i+" and "+j);
a[i][j]=Integer.parseInt(in.readLine());
}
}
catch(Exception e){}
System.out.println("Given adjacency matrix is ");
51

for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
System.out.print(a[i][j]+"\t");
System.out.println();
}
for(int i=1;i<=n;i++)
x[i]=0;
for(int i=2;i<n;i++)
{
m=i;
System.out.println("All possible combinations for m = "+i+" are ");
mcoloring(1);
}
}
void mcoloring(int k)
{
do
{
nextvalue(k);
if(x[k]==0) break;
if(k==n)
{
for(int i=1;i<=n;i++)

System.out.print(x[i]+"\t");
System.out.println();
}
else
mcoloring(k+1);
}while(true);
}
void nextvalue(int k)
{
int j;
do
{
x[k]=(x[k]+1)%(m+1);
if(x[k]==0) return;
for(j=1;j<=n;j++)
{
if((a[k][j]==1) && (x[k]==x[j]))
break;
}
if(j==n+1) return;
}while(true);
}
}
52

class Graphcoloring
{
public static void main(String args[ ])throws IOException
{
gcoloring g=new gcoloring();
g.read();
}
}

OUTPUT

53

RESULT
Thus the java program to implement graph coloring using backtracking has been
executed and output is verified successfully.

54

Вам также может понравиться