You are on page 1of 82

Ex No:1

MIN HEAP
Date:

AIM:
To implement Minheap using java.
ALGORITHM:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: Declare the size of heap as private and other member functions to insert, delete as
public.
Step 4: To insert the element into heap check whether the heap is full or not. if the keep is full
report that heap is full.
Step 5: If the heap is not full then to insert an element x into a heap, create a hole in the next
available position, otherwise the tree will not complete.
Step 6: If x can be placed in the hole without violating the heap order then we can insert in that
position.
Step 7: Otherwise slide the element that is in the holes parent node into the hole, thus bubbling
the hole up toward the root continue this process until x can be placed into the hole. this
is a strategy called percolate up.
Step 8: To delete an element, we have to check whether the heap is empty, or not. If the heap is
empty report that the heap is empty.
Step9: If the heap is not empty delete, have to delete the minimum, when the minimum is
removed, a hole is created at the root. It follows that the last element x in the heap must
move somewhere in the heap. If x can be placed in the hole then it is done.
Step 10: Otherwise slide the smaller of the holes children into the hole, thus pushing the hole
down one level. Repeat the step until x can be placed in the hole. This strategy is called
percolate down.
Step 11: Display the nodes in the Minheap.
Step 12: Stop the program.

SOURCE CODE:
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;
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)
{
int ans=1;
InputStreamReader xx = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(xx) ;
try{
MinHeap m=new MinHeap(50);
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.exit(0);
System.out.println("Exited Successfully");
default:
System.out.println("PLEASE ENTER THE VALID CASE\n");
System.out.println("\n");
break;
}
}
}
catch(IOException err)
{
System.out.println(err);
}
}
}

OUTPUT:
C:\jdk1.5\bin>javac MinHeap.java
C:\jdk1.5\bin>java MinHeap
1.INSERT
2.REMOVE
3.EXIT
Enter ur choice:1
ENTER THE SIZE
7
ENTER THE VALUE TO INSERT
80
30
35
40
26
21
32
THE VALUES ARE INSERTED SUCCESSFULLY
21 30 26 80 40 35 32
1.INSERT
2.REMOVE
3.EXIT
Enter ur choice:2
the min val(21)is deleted successfully
26 30 32 80 40 35
1.INSERT
2.REMOVE
3.EXIT
Enter ur choice:2
the min val(26)is deleted successfully
30 35 32 80 40
1.INSERT
2.REMOVE
3.EXIT
Enter ur choice:3

RESULT:
Thus the program to implement the Minheap was completed successfully.

Ex No:2
DEAPS
Date:
AIM:
To implement the basic operation on an Deaps using java.
ALGORITHM:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: Declare the size of Deaps as private and other member functions to insert, delete as
public.
Step 4: To insert the element into heap check whether the heap is full or not. if the keep is full
report that Deap is full.
Step 5: If the heap is not full then to insert an element x into a Deap, create a hole in the next
available position, otherwise the tree will not complete.
Step 6: If x can be placed in the hole without violating the Deap order then we can insert in that
position.
Step 7: Otherwise slide the element that is in the holes parent node into the hole, thus bubbling
the hole up toward the root continue this process until x can be placed into the hole. this
is a strategy called percolate up.
Step 8: To delete an element, we have to check whether the Deap is empty, or not. If the Deap is
empty report that the Deap is empty.
Step9: If the Deap is not empty delete, have to delete the minimum, when the minimum is
removed, a hole is created at the root. It follows that the last element x in the Deap must
move somewhere in the Deap. If x can be placed in the hole then it is done.
Step 10: Otherwise slide the smaller of the holes children into the hole, thus pushing the hole
down one level. Repeat the step until x can be placed in the hole. This strategy is called
percolate down.
Step 11: Display the nodes in the Deaps.
Step 12: Stop the program.

SOURCE CODE:
import java.io.*;
public class Deap {
// the underlying structure of the deap
protected static int[] tree;
private static int lastPos;
public static void Deap() {
tree = new int[1000];
lastPos = 1;
}
public static int size() {
return lastPos - 1;
}
public static boolean isEmpty() {
return (size() <= 0);
}
public static int elementAt(int index) {
return tree[index];
}
public static void insert(int e) {
lastPos++;
if (lastPos == 2) {
tree[lastPos] = e;
return;
}
if (lastPos == 3) {
if (tree[2]>(e)) {
tree[lastPos] = tree[2];
tree[2] = e;
}
else {
tree[lastPos] = e;
}
return;
}
if (isInMaxHeap(lastPos)) {
int pos = minPartner(lastPos);

if (e<(tree[pos])) {
tree[lastPos] = tree[pos];
minInsert(pos, e);
}
else {
maxInsert(lastPos, e);
}
}
else {
int pos = maxPartner(lastPos);
if (e>(tree[pos]) ) {
tree[lastPos] = tree[pos];
maxInsert(pos, e);
}
else {
minInsert(lastPos, e);
}
}
}
public static int removeMin() {
int min = tree[2];
if (size() > 1) {
tree[2] = tree[lastPos];
sinkInMin(2);
}
lastPos--;
return min;
}
public static int removeMax()
{
if (size() <= 1)
// empty MaxHeap, so look in MinHeap
return removeMin();
int max = tree[3];
if (size() >= 2) {
tree[3] = tree[lastPos];
sinkInMax(3);
}

lastPos--;
return max;
}
public static void reset() {
lastPos = 1;
}
public static boolean hasLeft(int index)
{
return ((2 * index) <= lastPos);
}
public static boolean hasRight(int index)
{
return ((2 * index + 1) <= lastPos);
}
public static int getLeft(int index)
{
return tree[2 * index];
}
public static int getRight(int index)
{
return tree[2 * index + 1];
}
private static void minInsert(int pos, int element) {
tree[pos] = element;
int act = pos;
// stop at MinHeaps root
while (act > 2) {
if (tree[act]>(tree[act / 2]) )
break;
exchange(act, act / 2);
// one level higher
act = act / 2;
}
}
private static void maxInsert(int pos, int element) {
tree[pos] = element;
int act = pos;
// stop at MaxHeaps root
while (act > 3) {
if (tree[act]<(tree[act / 2]) )
break;
exchange(act, act / 2);
// one level higher

10

act = act / 2;
}
}
private static void exchange(int index_1, int index_2) {
int temp = tree[index_1];
tree[index_1] = tree[index_2];
tree[index_2] = temp;
}
private static int minPartner(int i) {
int result = i - v(i);
if (2 * i >= lastPos && 2 * result <= lastPos)
return 2 * result;
else
return result;
}
private static int maxPartner(int i) {
int result = (i + v(i));
if (result <= lastPos)
return result;
else
return result / 2;
}
private static boolean isInMaxHeap(int pos) {
int posAtLevel = pos % (2 * v(pos));
return (posAtLevel >= v(pos));
}
private static int v(int i) {
int p = log2(i);
return (int) Math.pow(2, p - 1);
}
private static void sinkInMin(int index) {
while (true) {
if (!hasLeft(index) && !hasRight(index)) {
// external node position
// max partner
int pos = maxPartner(index);
if (isInMaxHeap(pos) && elementAt(index)>(elementAt(pos)) ) {
exchange(index, pos);

11

// swim(index);
}
break;
}
else if (!hasRight(index)) {
// but left child
if (elementAt(index)>(elementAt(2 * index)) ) {
exchange(index, 2 * index);
index = 2 * index;
}
else {
break;
}
}
else {
// both childs there, look for smaller ones
if (elementAt(2 * index)<(elementAt(2 * index + 1)) ) {
// smaller/equal left child
if (elementAt(index)>(elementAt(2 * index)) ) {
exchange(index, 2 * index);
index = 2 * index;
}
else {
break;
}
}
else {
// smaller right child
if (elementAt(index)>(elementAt(2 * index + 1)) ) {
exchange(index, 2 * index + 1);
index = 2 * index + 1;
}
else {
break;
}
}
}
}
}

12

private static void sinkInMax(int index) {


while (true) {
if (!hasLeft(index) && !hasRight(index)) {
// external node position
// max partner
int pos = minPartner(index);
if (!isInMaxHeap(pos) && elementAt(index)<(elementAt(pos)) ) {
exchange(index, pos);
// swim(index);
}
break;
}
else if (!hasRight(index)) {
// but left child
if (elementAt(index)<(elementAt(2 * index)) ) {
exchange(index, 2 * index);
index = 2 * index;
}
else {
break;
}
}
else {
// both childs there, look for greater ones
if (elementAt(2 * index)>(elementAt(2 * index + 1)) ) {
// greater/equal left child
if (elementAt(index)<(elementAt(2 * index)) ) {
exchange(index, 2 * index);
index = 2 * index;
}
else {
break;
}
}
else {
// greater right child
if (elementAt(index)<(elementAt(2 * index + 1)) ) {
exchange(index, 2 * index + 1);
index = 2 * index + 1;

13

}
else {
break;
}
}
}
}
}
protected static int log2(int i) {
return (int) (Math.log(i) / Math.log(2));
}
public static void disp()
{
System.out.println("deap[1]=NULL");
for(int k=2;k<=lastPos;k++)
System.out.println(" "+"Deap["+k+"]="+tree[k]+" ");
System.out.println();
}
public static void find(int u1)
{
for(int u=2;u<=lastPos;u++)
{
if(tree[u]==u1)
{
if(u==lastPos)
{
--lastPos;
for(int c1=2;c1<lastPos;c1++)
System.out.println(" "+"Deap["+c1+"]="+tree[c1]+" ");
}
else
{
for(int c=u;c<=lastPos;c++)
{
tree[c]=tree[c+1];
}lastPos--;
}
}
}
}
public static void main(String[] args)throws IOException
{

14

System.out.println("Deap");
int item,f,choice=1;
Deap();
System.out.println("1. Insertion...");
System.out.println("2. Deletion of min element...");
System.out.println("3. Deletion of max element...");
System.out.println("4. Deletion of an element...");
System.out.println("4. Exit..");
while(choice!=5)
{
System.out.println("Enter your choice:");
InputStreamReader in1=new InputStreamReader(System.in);
BufferedReader br1=new BufferedReader(in1);
String s1=br1.readLine();
choice=Integer.parseInt(s1);
switch(choice)
{
case 1:
System.out.print("\nEnter the item to be inserted:");
String s2=br1.readLine();
item=Integer.parseInt(s2);
insert(item);
break;
case 2:
int itemd=removeMin();
System.out.println("The deleted item is "+itemd);
break;
case 3:
int itemdm=removeMax();
System.out.println("The deleted item is "+itemdm);
break;
case 4:
System.out.println("enter the element to be deleted:");
String s3=br1.readLine();
f=Integer.parseInt(s3);
find(f);
case 5:
break;
}
disp();
}
}
}

15

OUTPUT:
C:\jdk1.5\bin>javac Deap.java
C:\jdk1.5\bin>java Deap
Deap
1. Insertion...
2. Deletion of min element...
3. Deletion of max element...
4. Deletion of an element...
4. Exit..
Enter your choice:
1
Enter the item to be inserted:80
deap[1]=NULL
Deap[2]=80
Enter your choice:
1
Enter the item to be inserted:30
deap[1]=NULL
Deap[2]=30
Deap[3]=80
Enter your choice:
1
Enter the item to be inserted:35
deap[1]=NULL
Deap[2]=30
Deap[3]=80
Deap[4]=35
Enter your choice:
1
Enter the item to be inserted:40
deap[1]=NULL
Deap[2]=30
Deap[3]=80
Deap[4]=35
Deap[5]=40
Enter your choice:
1
Enter the item to be inserted:26
deap[1]=NULL
Deap[2]=26
Deap[3]=80
Deap[4]=30
Deap[5]=40

16

Deap[6]=35
Enter your choice:
1
Enter the item to be inserted:21
deap[1]=NULL
Deap[2]=21
Deap[3]=80
Deap[4]=30
Deap[5]=26
Deap[6]=35
Deap[7]=40
Enter your choice:
1
Enter the item to be inserted:32
deap[1]=NULL
Deap[2]=21
Deap[3]=80
Deap[4]=30
Deap[5]=26
Deap[6]=35
Deap[7]=40
Deap[8]=32
Enter your choice:
2
The deleted item is 21
deap[1]=NULL
Deap[2]=26
Deap[3]=80
Deap[4]=30
Deap[5]=32
Deap[6]=35
Deap[7]=40
Enter your choice:
3
The deleted item is 80
deap[1]=NULL
Deap[2]=26
Deap[3]=40
Deap[4]=30
Deap[5]=32
Deap[6]=35
Enter your choice:
4
enter the element to be deleted:
30

17

deap[1]=NULL
Deap[2]=26
Deap[3]=40
Deap[4]=32
Deap[5]=35
Enter your choice:
5
deap[1]=NULL
Deap[2]=26
Deap[3]=40
Deap[4]=32
Deap[5]=35

18

RESULT:
Thus the program to implement the Deaps was completed successfully.

19

Ex No:3
LEFTIST HEAP
Date:

AIM:
To implement Leftist Heap using java.
ALGORITHM:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: Declare the size of heap as private and other member functions to insert, delete as
public.
Step 4: To insert the element into heap check whether the heap is full or not. if the keep is full
report that heap is full.
Step 5: If the heap is not full then to insert an element x into a heap, create a hole in the next
available position, otherwise the tree will not complete.
Step 6: If x can be placed in the hole without violating the heap order then we can insert in that
position.
Step 7: Otherwise slide the element that is in the holes parent node into the hole, thus bubbling
the hole up toward the root continue this process until x can be placed into the hole. This
is a strategy called percolate up.
Step 8: To delete an element, we have to check whether the heap is empty, or not. If the heap is
empty report that the heap is empty.
Step9: If the heap is not empty delete, have to delete the minimum, when the minimum is
removed, a hole is created at the root. It follows that the last element x in the heap must
move somewhere in the heap. If x can be placed in the hole then it is done.
Step 10: Otherwise slide the smaller of the holes children into the hole, thus pushing the hole
down one level. Repeat the step until x can be placed in the hole. This strategy is called
percolate down.
Step 11: Display the nodes in the Leftist Heap.
Step 12: Stop the program.

20

SOURCE CODE:
import java.io.*;
class node
{
public int data;
public node LC,RC;
public int shortest;
}
class minleftist
{
node root = null;
public void insert()
{
int newelt=0;
try
{
System.out.println("Enter the element:");
DataInputStream din=new DataInputStream(System.in);
newelt=Integer.parseInt(din.readLine());
}
catch(Exception e){}
node temp = new node();
temp.data=newelt;
temp.LC=temp.RC=null;
temp.shortest=1;
if(root==null)
root=temp;
else
root=meld(root,temp);
}
public node meld(node a, node b)
{
if(a.data > b.data)
{
node t;
t=a;
a=b;
b=t;
}

21

if(a.RC==null)
a.RC=b;
else
a.RC=meld(a.RC,b);
if((a.LC==null) || (a.LC.shortest < a.RC.shortest))
{
node t=new node();
t=a.LC;
a.LC=a.RC;
a.RC=t;
}
if(a.RC==null)
a.shortest=1;
else
a.shortest=a.RC.shortest+1;
return a;
}
public void remove()
{
System.out.println("Deleted element is "+root.data+"\n");
root=meld(root.LC,root.RC);
}
public void display()
{
if(root==null)
System.out.println("EMPTY");
else
{
System.out.println("\nIn Order");
dispin(root);
}
}
public void dispin(node currentnode)
{
if(currentnode!=null)
{
dispin(currentnode.LC);
System.out.println(currentnode.data+"
dispin(currentnode.RC);
}
}

"+"SHORTEST "+currentnode.shortest);

};

22

class LeftistTree
{
public static void main(String args[ ])throws IOException
{
int ch=0,cont=0;
minleftist m = new minleftist();
do
{
System.out.println("LEFTIST TREE 1. Insert 2. Delete");
DataInputStream din = new DataInputStream(System.in);
try
{
ch=Integer.parseInt(din.readLine());
}
catch(Exception e){}
if(ch==1)
{
m.insert();
m.display();
}
else if(ch==2)
{
m.remove();
m.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);
}
}

23

OUTPUT:
LEFTIST TREE 1. Insert 2. Delete
1
Enter the element:
50
In Order
50 SHORTEST 1
press 1 to continue:
1
LEFTIST TREE 1. Insert 2. Delete
1
Enter the element:
8
In Order
50 SHORTEST 1
8 SHORTEST 1
press 1 to continue:
1
LEFTIST TREE 1. Insert 2. Delete
1
Enter the element:
13
In Order
50 SHORTEST 1
8 SHORTEST 2
13 SHORTEST 1
press 1 to continue:
1
LEFTIST TREE 1. Insert 2. Delete
1
Enter the element:
11
In Order
50 SHORTEST 1
8 SHORTEST 2
13 SHORTEST 1
11 SHORTEST 1
press 1 to continue:
1
LEFTIST TREE 1. Insert 2. Delete
1
Enter the element:
20

24

In Order
13 SHORTEST 1
11 SHORTEST 2
20 SHORTEST 1
8 SHORTEST 2
50 SHORTEST 1
press 1 to continue:
1
LEFTIST TREE 1. Insert 2. Delete
1
Enter the element:
18
In Order
13 SHORTEST 1
11 SHORTEST 2
20 SHORTEST 1
8 SHORTEST 2
50 SHORTEST 1
18 SHORTEST 1
press 1 to continue:
1
LEFTIST TREE 1. Insert 2. Delete
1
Enter the element:
2
In Order
13 SHORTEST 1
11 SHORTEST 2
20 SHORTEST 1
8 SHORTEST 2
50 SHORTEST 1
18 SHORTEST 1
2 SHORTEST 1
press 1 to continue:
1
LEFTIST TREE 1. Insert 2. Delete
1
Enter the element:
7
In Order
13 SHORTEST 1
11 SHORTEST 2
20 SHORTEST 1
8 SHORTEST 2

25

50 SHORTEST 1
18 SHORTEST 1
2 SHORTEST 2
7 SHORTEST 1
press 1 to continue:
1
LEFTIST TREE 1. Insert 2. Delete
2
Deleted element is 2
In Order
13 SHORTEST 1
11 SHORTEST 2
20 SHORTEST 1
8 SHORTEST 2
50 SHORTEST 1
18 SHORTEST 1
7 SHORTEST 1
press 1 to continue:
12

26

RESULT:
Thus the program to implement the Leftist Heap was completed successfully.

27

Ex No: 4
AVL TREE
Date:

AIM:
To implement the basic operations on an AVL tree.
ALGORITHM:
Step 1: Find the place to insert the new node in the tree. Traverse the node from the
inserted position, until we end with a balance factor +1 or -1.Denote this node, as x. If a
duplicate key is found terminate the process.
Step 2: If node x was not found, make another pass from the root, updating the balance factors
as you go and terminate the process.
Step 3: If BF(X) = 1 and new node was inserted in Xs right sub tree or BF(X) =-1 and new node
was inserted in X ;s left sub tree , BF(X)=0, update the balance factor on path to X and
terminate the process.
Step 4: Otherwise, classify the imbalance at X and perform any of the 4 rotations.
Types of rotation in an AVL tree:

Left to Left rotation:

If BF(X) = 2 then this rotation is invoked.

Right to Right rotation:

If BF(X) =-2 then this rotation is invoked

Left to Right rotation:

If BF(X) = 2 and left trees BF(X) =-1 then this rotation is invoked.

Right to Left rotation:

If BF(X) =-2 and left trees BF(X) =1 then this rotation is invoked

28

Algorithm for delete:


Step 1: The node whose key is to be removed is located using a search, and the key is replaced
with its successor or predecessor.
Step 2: If removal of a node is done, an AVL tree may be unbalanced. The first unbalanced
ancestor of the removed node (the leaf node that contained the successor or predecessor)
is located and rearranged.

29

SOURCE CODE:
import java.io.*;
class node
{
public int data;
public node LC,RC;
public int bf;
}
class avltree
{
node root = null;
public boolean insert()
{
int newelt=0;
try
{
System.out.println("Enter the element:");
DataInputStream din=new DataInputStream(System.in);
newelt=Integer.parseInt(din.readLine());
}
catch(Exception e){}
//EMPTY TREE
if(root==null)
{
node y=new node();
y.data=newelt;
y.bf=0;
y.LC=null;
y.RC=null;
root=y;
return true;
}
//LOCATE INSERTION POINT
node f,a,q,p;
//f->a->q->p
node b,c;
//f->a's parent;a->node with+/- 1
int d;
//q->follows p;p->insertion point
node y=new node();
boolean found, unbalanced;
f=null;
a=root;
p=root;
q=null;
found=false;

30

while (p!=null && found!=true)


{
if(p.bf!=0) {a=p;f=q;}
if(newelt<p.data){q=p;p=p.LC;}
else if(newelt>p.data){q=p;p=p.RC;}
else {y=p;found=true;}
}
/* finally in the last iteration of the while loop
q will be the node to which p has to be attached
p will be null in the last iteration */
//INSERT & REBALANCE
//INSERT
if(found==false)
{
y.data=newelt;
y.bf=0;
y.LC=null;
y.RC=null;
if(newelt<q.data)
q.LC=y;
else
q.RC=y;
//REBALANCE AT node 'a' alone
if(newelt >a.data)
{p=a.RC;b=p;d=-1;}
else
{p=a.LC;b=p;d=1;}
//REBALANCE THRO' q TILL WE REACH THE NEW NODE
while(p!=y)
{
if(newelt > p.data)
{p.bf=-1;p=p.RC;}
else
{p.bf=1;p=p.LC;}
}
unbalanced=true;
if((a.bf==0)||((a.bf+d)==0))
{a.bf+=d;unbalanced=false;}
if(unbalanced==true)
{

31

if(d==1)
{
if(b.bf==1)
{
System.out.println("LL imbalance");
a.LC=b.RC;
b.RC=a;
a.bf=0;
b.bf=0;
}
else
{
System.out.println("LR imbalance");
c=b.RC;
b.RC=c.LC;
a.LC=c.RC;
c.LC=b;
c.RC=a;
switch(c.bf)
{
case 1:
a.bf=-1;
b.bf=0;
break;
case -1:
a.bf=0;
b.bf=1;
break;
case 0:
a.bf=0;
b.bf=0;
break;
}
c.bf=0;
b=c;
}
}
else
{
if(b.bf==-1)
{
System.out.println("RR imbalance");
a.RC=b.LC;
b.LC=a;
a.bf=0;
b.bf=0;

32

}
else
{
System.out.println("RL imbalance");
c=b.LC;
b.LC=c.RC;
a.RC=c.LC;
c.RC=b;
c.LC=a;
switch(c.bf)
{
case 1:
a.bf=0;
b.bf=-1;
break;
case -1:
a.bf=1;
b.bf=0;
break;
case 0:
a.bf=0;
b.bf=0;
break;
}
c.bf=0;
b=c;
}
}
if(f==null)
root=b;
else if(a==f.LC)
f.LC=b;
else if(a==f.RC)
f.RC=b;
}//end of unbalanced true
return true;
}//end of found false
return false;//elt already found
}
public void display()
{
if(root==null)
System.out.println("EMPTY");
else
{

33

System.out.println("\nIn Order");
dispin(root);
}
}
public void dispin(node currentnode)
{
if(currentnode!=null)
{
dispin(currentnode.LC);
System.out.println(currentnode.data+" "+"BF "+currentnode.bf);
dispin(currentnode.RC);
}
}
};
class AVLTreeImp
{
public static void main(String args[ ])throws IOException
{int ch=0,cont=0;
avltree a = new avltree();
do
{ System.out.println("AVLTREES 1. Insert ");
DataInputStream din = new DataInputStream(System.in);
try
{ch=Integer.parseInt(din.readLine());
}
catch(Exception e){}
if(ch==1)
{
boolean y=true;
y=a.insert();
a.display();
if(y==false)
System.out.println("Data already exists");
}
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);
}
}

34

OUTPUT:
AVLTREES 1. Insert
1
Enter the element:
3
In Order
3 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
2
In Order
2 BF 0
3 BF 1
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
1
LL imbalance
In Order
1 BF 0
2 BF 0
3 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
4
In Order
1 BF 0
2 BF -1
3 BF -1
4 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:

35

5
RR imbalance
In Order
1 BF 0
2 BF -1
3 BF 0
4 BF 0
5 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
6
RR imbalance
In Order
1 BF 0
2 BF 0
3 BF 0
4 BF 0
5 BF -1
6 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
7
RR imbalance
In Order
1 BF 0
2 BF 0
3 BF 0
4 BF 0
5 BF 0
6 BF 0
7 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
16
In Order
1 BF 0
2 BF 0

36

3 BF 0
4 BF -1
5 BF 0
6 BF -1
7 BF -1
16 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
15
RL imbalance
In Order
1 BF 0
2 BF 0
3 BF 0
4 BF -1
5 BF 0
6 BF -1
7 BF 0
15 BF 0
16 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
14
RL imbalance
In Order
1 BF 0
2 BF 0
3 BF 0
4 BF -1
5 BF 0
6 BF 1
7 BF 0
14 BF 0
15 BF 0
16 BF 0
press 1 to continue:
1
AVLTREES 1. Insert

37

1
Enter the element:
13
RR imbalance
In Order
1 BF 0
2 BF 0
3 BF 0
4 BF 0
5 BF 0
6 BF 1
7 BF 0
13 BF 0
14 BF 1
15 BF 1
16 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
12
LL imbalance
In Order
1 BF 0
2 BF 0
3 BF 0
4 BF 0
5 BF 0
6 BF 1
7 BF 0
12 BF 0
13 BF 0
14 BF 0
15 BF 1
16 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
11
LL imbalance

38

In Order
1 BF 0
2 BF 0
3 BF 0
4 BF 0
5 BF 0
6 BF 1
7 BF 0
11 BF 0
12 BF 1
13 BF 0
14 BF 0
15 BF 0
16 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
10
LL imbalance
In Order
1 BF 0
2 BF 0
3 BF 0
4 BF 0
5 BF 0
6 BF 1
7 BF 0
10 BF 0
11 BF 0
12 BF 0
13 BF 0
14 BF 0
15 BF 0
16 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
8
In Order
1 BF 0
2 BF 0

39

3 BF 0
4 BF 0
5 BF 0
6 BF 1
7 BF -1
8 BF 0
10 BF 1
11 BF 1
12 BF 0
13 BF 1
14 BF 0
15 BF 0
16 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
9
LR imbalance
In Order
1 BF 0
2 BF 0
3 BF 0
4 BF 0
5 BF 0
6 BF 1
7 BF -1
8 BF 0
9 BF 0
10 BF 0
11 BF 1
12 BF 0
13 BF 1
14 BF 0
15 BF 0
16 BF 0
press 1 to continue:
1
AVLTREES 1. Insert
1
Enter the element:
16
In Order

40

1 BF 0
2 BF 0
3 BF 0
4 BF 0
5 BF 0
6 BF 1
7 BF -1
8 BF 0
9 BF 0
10 BF 0
11 BF 1
12 BF 0
13 BF 1
14 BF 0
15 BF 0
16 BF 0
Data already exists
press 1 to continue:
12

41

RESULT:
Thus the AVL Tree has been implemented successfully.

42

Ex No: 5
B-TREE
Date:

AIM:
To implement the basic operations in a binary tree.
ALGORITHM:
Algorithm for Insert:
Step 1: Check whether the root node of the binary tree is NULL.
Step 2: If the condition is true, it means, that the binary tree is empty, hence consider the new
node as the root node. Otherwise, follow the next steps.
Step 3: If the content of the new node data is equal to the root node data, insertion operation is
terminated (because of duplication).
Step 4: If the content of the new node data is lesser than the root node data, check whether the
left child of the root node is NULL. If the condition is true, insert the new data and
terminate the process. Otherwise, consider the left child of the root node as the root node
and check for the three conditions again.
Step 5: If the content of the new node data is greater than the root node data, check whether the
right child of the root node is NULL. If the condition is true, insert the new data and
terminate the process. Otherwise, consider the right child of the root node as the root
node and check for the three conditions again.
Algorithm for delete:
Deleting the leaf node
Deleting the node with only one child
Deleting the node with two children

43

Deleting the leaf node:


Step 1: Search the parent of the leaf node, and make the link to the leaf node as Null.
Step 2: Release the memory for the deleted node.
Deleting the node with only one child:
Step 1: Search the parent of the node to be deleted (with only one child)
Step 2: Assign the link of the parent node to the child of the node to be deleted;
Step 3: Release the memory for the deleted node.
Deleting the node with two children:
Step 1: Search the parent of the node to be deleted (with two children)
Step 2: Copy the content of the in order successor to the node to be deleted (with two children)
Step 3: Delete the in order successor node. If the in order successor node has no child, follow the
steps given in the deleting the leaf node. If the in order successor node has only one
child, follow the steps given in the deleting the node with one child.
Step 4: Release the memory for the inorder successor node.
Step 5: Replace the contents of the node to be deleted with the copy of the content of the inorder
successor node.

44

SOURCE CODE:
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)
{
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)
{

45

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;
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();

46

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;
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;

47

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);
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);
}
}

48

OUTPUT:
B-Trees
Enter the element
52
data1::52 data2::0 Address::bnode@923e30 parent::null
To continue...press 1
1
Enter the element
45
data1::45 data2::52 Address::bnode@923e30 parent::null
To continue...press 1
1
Enter the element
89
data1::45 data2::0 Address::bnode@130c19b parent::bnode@923e30
data1::89 data2::0 Address::bnode@1f6a7b9 parent::bnode@923e30
data1::52 data2::0 Address::bnode@923e30 parent::null
To continue...press 1
1
Enter the element
12
data1::12 data2::45 Address::bnode@130c19b parent::bnode@923e30
data1::89 data2::0 Address::bnode@1f6a7b9 parent::bnode@923e30
data1::52 data2::0 Address::bnode@923e30 parent::null
To continue...press 1
1
Enter the element
56
data1::12 data2::45 Address::bnode@130c19b parent::bnode@923e30
data1::56 data2::89 Address::bnode@1f6a7b9 parent::bnode@923e30
data1::52 data2::0 Address::bnode@923e30 parent::null
To continue...press 1
1
Enter the element
1
data1::1 data2::0 Address::bnode@7d772e parent::bnode@923e30
data1::45 data2::0 Address::bnode@11b86e7 parent::bnode@923e30
data1::56 data2::89 Address::bnode@1f6a7b9 parent::bnode@923e30
data1::12 data2::52 Address::bnode@923e30 parent::null
To continue...press 1
1
Enter the element
32
data1::1 data2::0 Address::bnode@7d772e parent::bnode@923e30
data1::32 data2::45 Address::bnode@11b86e7 parent::bnode@923e30

49

data1::56 data2::89 Address::bnode@1f6a7b9 parent::bnode@923e30


data1::12 data2::52 Address::bnode@923e30 parent::null
To continue...press 1
1
Enter the element
25
data1::1 data2::0 Address::bnode@7d772e parent::bnode@35ce36
data1::25 data2::0 Address::bnode@757aef parent::bnode@35ce36
data1::12 data2::0 Address::bnode@35ce36 parent::bnode@923e30
data1::45 data2::0 Address::bnode@d9f9c3 parent::bnode@9cab16
data1::56 data2::89 Address::bnode@1f6a7b9 parent::bnode@9cab16
data1::52 data2::0 Address::bnode@9cab16 parent::bnode@923e30
data1::32 data2::0 Address::bnode@923e30 parent::null
To continue...press 1
1
Enter the element
60
data1::1 data2::0 Address::bnode@7d772e parent::bnode@35ce36
data1::25 data2::0 Address::bnode@757aef parent::bnode@35ce36
data1::12 data2::0 Address::bnode@35ce36 parent::bnode@923e30
data1::45 data2::0 Address::bnode@d9f9c3 parent::bnode@9cab16
data1::56 data2::0 Address::bnode@1a46e30 parent::bnode@9cab16
data1::89 data2::0 Address::bnode@3e25a5 parent::bnode@9cab16
data1::52 data2::60 Address::bnode@9cab16 parent::bnode@923e30
data1::32 data2::0 Address::bnode@923e30 parent::null
To continue...press 1
1
Enter the element
83
data1::1 data2::0 Address::bnode@7d772e parent::bnode@35ce36
data1::25 data2::0 Address::bnode@757aef parent::bnode@35ce36
data1::12 data2::0 Address::bnode@35ce36 parent::bnode@923e30
data1::45 data2::0 Address::bnode@d9f9c3 parent::bnode@9cab16
data1::56 data2::0 Address::bnode@1a46e30 parent::bnode@9cab16
data1::83 data2::89 Address::bnode@3e25a5 parent::bnode@9cab16
data1::52 data2::60 Address::bnode@9cab16 parent::bnode@923e30
data1::32 data2::0 Address::bnode@923e30 parent::null
To continue...press 1
12

50

RESULT:
Thus the basic operation of a Binary Tree has been implemented successfully.

51

Ex No: 6
TRIES
Date:

AIM:
To implement Tries using java.
ALGORITHM:
Algorithm for Insert:
Step 1: Start the program.
Step 2: Check whether the root node of the tree is NULL.
Step 3: If the condition is true, it means, that the tree is empty, hence consider the new node as
the root node. Otherwise, follow the next steps.
Step 4: If the content of the new node data is equal to the root node data, insertion operation is
terminated (because of duplication).
Step 5: If the content of the new node data is lesser than the root node data, check whether the
left child of the root node is NULL. If the condition is true, insert the new data and
terminate the process. Otherwise, consider the left child of the root node as the root node
and check for the three conditions again.
Step 6: If the content of the new node data is greater than the root node data, check whether the
right child of the root node is NULL. If the condition is true, insert the new data and
terminate the process. Otherwise, consider the right child of the root node as the root
node and check for the three conditions again.
Step 7: Stop the program.

52

SOURCE CODE:
import java.io.*;
class node
{
public int tag,level;
//tag for ptr node 1;data node 0; level starts with 1
public int data;
//for data node
public node LC,RC,par;
//for ptr node
}
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) //temp is a ptr node
{
if((item & 1)==0)
{
temp=temp.LC;
item=item >> 1;
}
else
{
temp=temp.RC;
item=item >> 1;
}
}
else //temp is a data node
{
if(key==temp.data)
{
return temp;
}
else break;
}
}
return null; //the element not in the trie

53

}
public void insert()
{
int key=0;
try
{
System.out.println("Enter the element:");
DataInputStream din=new DataInputStream(System.in);
key=Integer.parseInt(din.readLine());
}
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 //trie not empty
{
node temp=find(key);
if(temp==null) //key not in trie
{
temp=cptr;
//cptr points to a data node
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;
//Branching takes place here
while ( (k1 & 1 ) ==(k2 & 1 ))
{
kk1=k1;
k1=k1 >> 1;
k2=k2 >> 1;
//skip already existing branches

54

if(lv>=temp.level)
{
node n3=new node();
n3.tag=1;
//Branch the new ptr node
//towards left
if ( (kk1 & 1)==0)
{
temp.LC=n3;
temp.RC=null;
n3.level=temp.level+1;
}
//Branch the new ptr node
//towards right
else
{
temp.RC=n3;
temp.LC=null;
n3.level=temp.level+1;
}
n3.par=temp;
temp=n3;
lv++;
}
else
lv++;
}
//Branching the data nodes with n1 as a LC
if( (k1 & 1)==0)
{
temp.LC=n1;
temp.RC=n2;
n1.level=n2.level=temp.level+1;
}
//Branching the data nodes with n1 as a RC
else
{
temp.LC=n2;
temp.RC=n1;
n1.level=n2.level=temp.level+1;
}

55

//Setting the par pointer of new data nodes


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;
}
}// end of if temp== null
else
System.out.println("Element already exists");
}//end of else trie not empty
}//end of insert
public void display()
{
if(root==null)
System.out.println("EMPTY");
else
{
System.out.println("\nIn Order");
dispin(root);
}
}
public void dispin(node currentnode)
{
if(currentnode!=null)
{
dispin(currentnode.LC);
System.out.println(currentnode.data+"
"+"TAG-"+currentnode.tag);
dispin(currentnode.RC);
}
}

"+"LEVEL- "+currentnode.level+"

};

56

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);
}
}

57

OUTPUT:
TRIES 1. Insert
1
Enter the element:
1232
In Order
1232 LEVEL- 1 TAG-0
press 1 to continue:
1
TRIES 1. Insert
1
Enter the element:
4451
In Order
1232 LEVEL- 2 TAG-0
0 LEVEL- 1 TAG-1
4451 LEVEL- 2 TAG-0
press 1 to continue:
1
TRIES 1. Insert
1
Enter the element:
1243
In Order
1232 LEVEL- 2 TAG-0
0 LEVEL- 1 TAG-1
0 LEVEL- 2 TAG-1
4451 LEVEL- 5 TAG-0
0 LEVEL- 4 TAG-1
1243 LEVEL- 5 TAG-0
0 LEVEL- 3 TAG-1
press 1 to continue:
1
TRIES 1. Insert
1
Enter the element:
1015
In Order
1232 LEVEL- 2 TAG-0
0 LEVEL- 1 TAG-1
0 LEVEL- 2 TAG-1
4451 LEVEL- 5 TAG-0
0 LEVEL- 4 TAG-1
1243 LEVEL- 5 TAG-0

58

0 LEVEL- 3 TAG-1
1015 LEVEL- 4 TAG-0
press 1 to continue:
1
TRIES 1. Insert
1
Enter the element:
1942
In Order
1232 LEVEL- 3 TAG-0
0 LEVEL- 2 TAG-1
1942 LEVEL- 3 TAG-0
0 LEVEL- 1 TAG-1
0 LEVEL- 2 TAG-1
4451 LEVEL- 5 TAG-0
0 LEVEL- 4 TAG-1
1243 LEVEL- 5 TAG-0
0 LEVEL- 3 TAG-1
1015 LEVEL- 4 TAG-0
press 1 to continue:
1
TRIES 1. Insert
1
Enter the element:
1941
In Order
1232 LEVEL- 3 TAG-0
0 LEVEL- 2 TAG-1
1942 LEVEL- 3 TAG-0
0 LEVEL- 1 TAG-1
1941 LEVEL- 3 TAG-0
0 LEVEL- 2 TAG-1
4451 LEVEL- 5 TAG-0
0 LEVEL- 4 TAG-1
1243 LEVEL- 5 TAG-0
0 LEVEL- 3 TAG-1
1015 LEVEL- 4 TAG-0
press 1 to continue:
1
TRIES 1. Insert
1
Enter the element:
1055
In Order
1232 LEVEL- 3 TAG-0
0 LEVEL- 2 TAG-1

59

1942 LEVEL- 3 TAG-0


0 LEVEL- 1 TAG-1
1941 LEVEL- 3 TAG-0
0 LEVEL- 2 TAG-1
4451 LEVEL- 5 TAG-0
0 LEVEL- 4 TAG-1
1243 LEVEL- 5 TAG-0
0 LEVEL- 3 TAG-1
1015 LEVEL- 5 TAG-0
0 LEVEL- 4 TAG-1
1055 LEVEL- 5 TAG-0
press 1 to continue:
1
TRIES 1. Insert
1
Enter the element:
1243
Element already exists
In Order
1232 LEVEL- 3 TAG-0
0 LEVEL- 2 TAG-1
1942 LEVEL- 3 TAG-0
0 LEVEL- 1 TAG-1
1941 LEVEL- 3 TAG-0
0 LEVEL- 2 TAG-1
4451 LEVEL- 5 TAG-0
0 LEVEL- 4 TAG-1
1243 LEVEL- 5 TAG-0
0 LEVEL- 3 TAG-1
1015 LEVEL- 5 TAG-0
0 LEVEL- 4 TAG-1
1055 LEVEL- 5 TAG-0
press 1 to continue:
12

60

RESULT:

Thus the implementation of Tries has been completed successfully.

61

Ex No: 7
QUICK SORT
Date: 4-11-09

AIM:
To sort the given number in ascending order using quick sort.
ALGORITHM:
Step 1: Start the program.
Step 2:Include the necessary packages.
Step 3: Declare the number of elements that is to be sorted.
Step 4: If the number of elements is 0 or 1 then return.
Step 5: Divide the given array into two and take middle element X as the pivot in the array A.
Step 6: Partition A-[X] (the remaining elements in S) into two disjoint groups
A1 = (y belongs to A-[X]/y<=X) and A2=(y belongs to A-[X]/y>=X).
Step 7: Return (quicksort(A1) followed by X followed by quicksort(A2))
Step 8: Display the sorted list.
Step 9: Stop the program.

62

SOURCE CODE:
import java.io.*;
public class Quick
{
public static void main(String args[]) throws IOException
{
int [] array=new int[50];
int i;
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream) ;
System.out.println("Quick Sort\n");
System.out.println(" Enter The Size Of array:");
String nn=bufRead.readLine();
int n = Integer.parseInt(nn);
System.out.println("Enter The Values Of array:\n");
for(i=0;i<n;i++)
{
String ms=bufRead.readLine();
int mss = Integer.parseInt(ms);
array[i]=mss;
}
System.out.println("Values Before the sort:\n");
for(i = 0; i <n; i++)
System.out.print( array[i]+" ");
System.out.println();
quick_srt(array,0,n-1);
System.out.print("Values after the sort:\n");
for(i = 0; i <n; i++)
System.out.print(array[i]+" ");
System.out.println();
System.out.println("PAUSE");
}
public static void quick_srt(int array[],int low, int n)
{
int lo = low;
int hi = n;
if (lo >= n)
{
return;
}
int mid = array[(lo + hi) / 2];

63

while (lo < hi)


{
while (lo<hi && array[lo] < mid)
{
lo++;
}
while (lo<hi && array[hi] > mid)
{
hi--;
}
if (lo < hi)
{
int T = array[lo];
array[lo] = array[hi];
array[hi] = T;
}
}
if (hi < lo)
{
int T = hi;
hi = lo;
lo = T;
}
quick_srt(array, low, lo);
quick_srt(array, lo == low ? lo+1 : lo, n);
}
}

64

OUTPUT:
C:\jdk1.5\bin>javac Quicksort.java
C:\jdk1.5\bin>java Quicksort
Quick Sort
Enter The Size Of array:
9
Enter The Values Of array:
90
84
26
59
98
21
15
19
74
Values Before the sort:
90 84 26 59 98 21 15 19 74
Values after the sort:
15 19 21 26 59 74 84 90 98

65

RESULT:
Thus the quick sort algorithm has been implemented successfully.

66

Ex No: 8
CONVEX HULL
Date:

AIM:
To implement Convex hull algorithm using java.
ALGORITHM:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: Declare the number of points that polygon containing all the points S.
Step 4: If x[i] is point out the element and x[j] is the next element.
Step 5: the point p in element of lowest y-coordinates.
Step 6: if((x[i]>x[j]) || ((x[i]==x[j]) && (y[i]>y[j]))) swap(i, j);
Step 7: The points according to the angle made with p and the x-axis.
Step 8: Display the convex polygon points .
Step 9: Stop the program.

67

SOURCE CODE:
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();
}
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)

68

{
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
{
if((c=='L' && deg>degree)||(c!='L' && deg<degree)
||(degree==deg && x[i]<x[next]))
{

69

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();
}
}

70

OUTPUT:
Enter number of points:
4
Enter x and y coordinates for
point 1
2
6
point 2
7
8
point 3
1
4
point 4
2
10
Boundary points are
(1, 4)
(2, 10)
(7, 8)

71

RESULT:
Thus the Convex Hull algorithm has been executed successfully.

72

Ex No: 9
0/1 KNAPSACK USING DYNAMIC PROGRAMMING
Date:

AIM:
To implement Knapsack problem using java.
ALGORITHM:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: Declare m is the size of knapsack and n is number of weights and profits.
Step 4: w[] and p[] are the weights and profits.
Step 5: p[i]/w[i] p[i+1]/w[i+1]. fw is the final weight of knapsack.
Step 6: fp is the final maximum profit.
Step 7: x[k]=0 if w[k] is not in the knapsack;else x[k]=1.
Step 8: Print the weight and final profit.
Step 9: Stop the program.

73

SOURCE CODE:
import java.util.*;
import java.io.*;
import java.lang.*;
public class Knapsack01{
static int n=5, W;
static obj st[];
public static BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
static class obj
{
int weight;
int profit;
}
public static void main(String args[]) throws IOException{
int i=0;
System.out.println("Knap Sack Problem\n------------------\n");
System.out.print("Enter total number of objects: ");
n = Integer.parseInt( br.readLine() );
System.out.print("Enter the maximum weight sack can take: ");
W = Integer.parseInt( br.readLine() );
st = new obj[n+1];
st[0] = new obj();
st[0].weight = st[0].profit = 0;
for(i=1; i<=n; i++)
{
st[i] = new obj();
System.out.print("For Object "+(i)+" :-\n\tWeight: ");
st[i].weight = Integer.parseInt(br.readLine());
System.out.print("\tProfit: ");
st[i].profit = Integer.parseInt(br.readLine());
}
System.out.print("\nOptimal Solution is : { ");
simple_fill();
}
static void simple_fill() {
int [][]s = new int[n+1][W+1];
for (int w = 0; w<= W; w++) s[0][w] = 0;
for(int i=0; i<=n; i++) s[i][0]=0;
for(int i=1; i<=n; i++)
for (int w = 0; w<= W; w++)

74

if (st[i].weight <= w)
{
if (st[i].profit + s[i-1][w-st[i].weight] > s[i-1][w])
s[i][w] = st[i].profit + s[i-1][w- st[i].weight];
else
s[i][w] = s[i-1][w];
}
else
s[i][w] = s[i-1][w];
int i = n;
int k = W;
int prof = 0;
while((i>0)&&(k>0))
{
if (s[i][k] != s[i-1][k])
{
System.out.print(i+":("+st[i].weight+", Rs."+st[i].profit+"), ");
k = k - st[i].weight;
prof += st[i].profit;
}
i--;
}
System.out.print(" }\nIt will yield a profit of Rs."+ prof);
}
}

75

OUTPUT:
C:\jdk1.5\bin>javac knapsack.java
C:\jdk1.5\bin>java knapsack
Knap Sack Problem
Enter total number of objects: 3
Enter the maximum weight sack can take: 100
For Object 1 :Weight: 50
Profit: 100
For Object 2 :Weight: 100
Profit: 500
For Object 3 :Weight: 25
Profit: 100
Optimal Solution is : { 2:(100, Rs.500), }
It will yield a profit of Rs.500

76

RESULT:
Thus the knapsack problem has been implemented successfully.

77

Ex.No:10
GRAPH COLORING USING BACKTRACKING
Date:

AIM:
To implement Graph coloring using java.
ALGORITHM:
Step 1: Start the program.
Step 2: Include the necessary packages.
Step 3: To get the number of vertices and colors.
Step 4: x[i] is the number of vertices and k is the index of the next vertex to color.
Step 5: Generate all legal assignment for x[k] nextvalue(k).
Step 6: if(x[k]=0) then no new color possible
Step 7: if(k=n) then almost m colors have been used to color then n vertices.
Step 8: Display all the nodes and possible colors .
Step 9: Stop the program.

78

SOURCE CODE:
import java.io.*;
public class GraphColoring
{
static int [][] G;
static int [] x;
static int n, m;
static boolean found = false;
public static BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException
{
System.out.println("\t\t\t\tGRAPH COLORING");
System.out.print("\nEnter the number of the vertices: ");
n = Integer.parseInt(br.readLine());
G = new int[n+1][n+1];
x = new int[n+1];
System.out.print("\nIf edge between the following vertices enter 1 else 0:\n");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if((i!=j)&&(i<j))
{
System.out.print(i+" and "+j+": ");
G[j][i]=G[i][j] = Integer.parseInt(br.readLine());
}
if(i==j)
G[i][j]=0;
}
System.out.print("\nEnter the number of colors available: ");
m = Integer.parseInt(br.readLine());
System.out.println("\nSolution:");
mColoring(1);
if (found == false)
System.out.println("No Solution possible!");
}
static void mColoring(int k)
{
while(true)
{
NextValue(k);
if(x[k] == 0)

79

return;
if(k == n)
{
for(int i=1; i<=k;i++)
System.out.print(x[i]+" ");
System.out.println();
found = true;
return;
}
else
mColoring(k+1);
}
}
static void NextValue(int k)
{
int j;
while(true)
{
x[k] = (x[k]+1)%(m+1);
if(x[k]==0)
return;
for(j=1; j<=n; j++)
if( (G[k][j] != 0) && (x[k] == x[j]) )
break;
if(j == n+1)
return;
}
}
}

80

OUTPUT:
C:\jdk1.5\bin>javac graphcoloring.java
C:\jdk1.5\bin>java graphcoloring
GRAPH COLORING
Enter the number of the vertices: 5
If edge between the following vertices enter 1 else 0:
1 and 2: 1
1 and 3: 1
1 and 4: 0
1 and 5: 1
2 and 3: 0
2 and 4: 1
2 and 5: 1
3 and 4: 1
3 and 5: 1
4 and 5: 1
Enter the number of colors available: 3
Solution:
12213
23321

81

RESULT:
Thus the Graph coloring has been implemented successfully.

82

You might also like