SlideShare une entreprise Scribd logo
1  sur  63
Télécharger pour lire hors ligne
Ex No: 1
                                              MIN HEAP
Date:




AIM

        To implement the min heap structure with insert and delete minimum operation using
Java program




ALGORITHM

    Step 1:     start the program by creating function with min heap property

    Step 2:     two functions namely insert() and deletemin() are created

    Step 3:     The insert () is used to insert new element in the tree structure with heap
                property.

    Step 4:     The deletemin() is used to delete the minimum element which is usually a root
                node.

    Step 5:     The two operations are performed satisfying heapness and completeness
                property.

    Step 6:     End of the program.




                                                       1
PROGRAM:
                                                     MIN HEAP


import java.io.*;
class heapalg
{
   int maxsize=100,size;
   int[] h=new int[maxsize];
   public int leftchild(int i)
   {
        return 2*i;
   }
   public int rightchild(int i)
   {
        return 2*i + 1;
   }
   public int parent(int i)
   {
        return i/2;
   }
   public boolean isleaf(int i)
   {
     return ((i<=size) && (i>size/2));
   }
   public void swap(int i,int j)
   {
        int t;
        t=h[i];h[i]=h[j];h[j]=t;
   }
   public void display()
   {
       System.out.println("The heap elements are:"+"n");
       for(int i=1;i<=size;i++)
          System.out.println("n"+h[i]);
   }
   public void insert()
   {
      size++;
      if(size>maxsize)
        System.out.println("Heapfull");
      else
      {
         try
         {
                  System.out.println("Enter the element:");
                  DataInputStream din=new DataInputStream(System.in);
                  h[size]=Integer.parseInt(din.readLine());
         }
         catch(Exception e){}
         insertelt(size);
      }
   }
   public void insertelt(int i)
   {
              while ((h[parent(i)]>h[i]))
       {
          int par=parent(i);
          swap(par,i);
          i=par;




                                                             2
}

     public void delete()
     }

     {
         if(size==0)
           System.out.println("Heapempty");
          else
          {
           System.out.println("The deleted min elt:"+h[1]);
           h[1]=h[size--];
           if(size!=0)
             percolate(1);
          }
       }
     public void percolate(int i)
     {
         while(!isleaf(i))
         {
           int small=leftchild(i);
           if( (small<size)&& h[small] > h[small+1])
              small+=1;
           if(h[small] < h[i])
                swap(small,i);
           i=small;
        }
    }

class minheap
}

{
     public static void main(String args[]) throws IOException
     {
       int ch=0,cont=0;
       heapalg h1=new heapalg();
       do
       {
          System.out.println("MIN HEAP 1.Insert 2.Delete Min");
          DataInputStream din=new DataInputStream(System.in);
          try
          {
            ch=Integer.parseInt(din.readLine());
          }
          catch(Exception e){}
          if(ch==1)
          {
            h1.insert();
            h1.display();
          }
          else if(ch==2)
          {
             h1.delete();
             h1.display();
          }
          else
          {
              System.out.println("Enter the correct choice");
          }
          System.out.println("press 1 to continue:");
          try
          {
            cont=Integer.parseInt(din.readLine());
                                                              3
}
         catch(Exception e){}
        }while(cont==1);
    }
}




                                4
OUTPUT:
--------
MIN HEAP 1.Insert 2.Delete Min
1
Enter the element:
42
The heap elements are:
42
press 1 to continue:
1
MIN HEAP 1.Insert 2.Delete Min
1
Enter the element:
3
The heap elements are:
3
42
press 1 to continue:
1
MIN HEAP 1.Insert 2.Delete Min
1
Enter the element:
86
The heap elements are:
3
42
86
press 1 to continue:
1
MIN HEAP 1.Insert 2.Delete Min
1
Enter the element:
2
The heap elements are:
2
3
86
42
press 1 to continue:
1
MIN HEAP 1.Insert 2.Delete Min
2
The deleted min elt:2
The heap elements are:
3
42
86
press 1 to continue:
12




.



                                 5
Ex No: 2
                                                DEAPS
Date:


AIM

        To implement program for deaps structure with insert and delete operations using
Java.




ALGORITHM

    Step 1:     Start the program by creating Deap Structure.

    Step 2:     Perform insert and delete functions.

    Step 3:     The insert() is done with 2 methods namely maxinsert() and mininsert().

    Step 4:     The delete() is done with 2 methods namely deletemax() and deletemin()

    Step 5:     The leftChild and rightChild are compared and the appropriate element is
                placed in the root node.

    Step 6:     After the insert and delete operation Deap elements are displayed.

    Step 7:     Stop of the program.




                                                       6
PROGRAM

DEAPS
import java.io.*;
class deapsalg
{
   int maxsize=100,size;
   int[] h=new int[maxsize+1];
   public int leftchild(int i)
   {
        return 2*i;
   }
   public int rightchild(int i)
   {
        return 2*i + 1;
   }
   public int parent(int i)
   {
        return i/2;
   }
   public boolean isleaf(int i)
   {
     return ((i<=size) && (i>size/2));
   }
   public void swap(int i,int j)
   {
        int t;
        t=h[i];h[i]=h[j];h[j]=t;
   }
   public void display()
   {
       System.out.println("The deaps elements are:");
       for(int i=1;i<=size+1;i++)
          System.out.println("n"+h[i]);
   }
   public int MaxHeap(int i)
   {
      int t=i;
      while(t!=2 && t!=3)
        t=t/2;
      if(t==2)
      {
        return 0;
      }
      else
      {
        return 1;
      }
   }
   public int MinPartner(int p)
   {
        int powvalue=(int) ((Math.floor(Math.log(p)/Math.log(2)))-1);
        int partner=p-(int)(Math.pow(2,powvalue));
        return partner;
   }

  public int MaxPartner(int p)
  {
      int powvalue=(int) ((Math.floor(Math.log(p)/Math.log(2)))-1);




                                                               7
int partner=p+(int)(Math.pow(2,powvalue));
     if(partner>size+1)
        partner/=2;
     return partner;

public void MinInsert(int i)
}

{
    while (parent(i)!=1 && (h[parent(i)]>h[i]))
    {
      int par=parent(i);
      swap(par,i);
      i=par;
    }

public void MaxInsert(int i)
}

{
    while (parent(i) !=1 && (h[parent(i)]<h[i]))
    {
      int par=parent(i);
      swap(par,i);
      i=par;
    }

public void insert()
}

{
    int newelt=0;
    size++;
    if(size>maxsize)
      System.out.println("Deap full");
    else
    {
      try
       {
               System.out.println("Enter the element:");
               DataInputStream din=new DataInputStream(System.in);
               newelt=Integer.parseInt(din.readLine());
       }
       catch(Exception e){}

      if(size==1)
      {
        h[2]=newelt;
       return;
      }
      int p=size+1;
      h[p]=newelt;
      switch(MaxHeap(p))
      {
         case 1:
             int partner=MinPartner(p);
             if(h[partner]>h[p])
             {
                swap(p,partner);
                MinInsert(partner);
             }
             else
                MaxInsert(p);
             break;
         case 0:                                             8
             partner=MaxPartner(p);
if(h[partner]<h[p])
             {
                swap(p,partner);
                MaxInsert(partner);
             }
             else
                MinInsert(p);
             break;
         default:
             System.out.println("ERROR");
        }
    }

public void deletemin()
}

{
    if(size==0)
        System.out.println("Deap empty");
    else
    {
        System.out.println("The deleted min elt:"+ h[2]);
        int i;
        int p=size+1;
        int t=h[p];
        size--;
        int small;
        for( i=2;2*i<=size+1;i=small)
        {
            if(h[rightchild(i)]<h[leftchild(i)])
               small=rightchild(i);
            else
                   small=leftchild(i);
            h[i]=h[small];
        }
         p=i; t
        h[p]=t;
        for(i=2;i<=size+1;i++)
       {
         switch(MaxHeap(i))
         {
            case 1:
                int partner=MinPartner(i);
                if(h[partner]>h[i])
                {
                    swap(i,partner);
                    MinInsert(partner);
                }
                else
                   MaxInsert(i);
                break;
            case 0:
                partner=MaxPartner(i);
                if(h[partner]<h[i])
                {
                    swap(i,partner);
                    MaxInsert(partner);
                }
                else
                   MinInsert(i);
                break;
           default:


                                                            9
System.out.println("ERROR");
                }
            }
        }

    public void deletemax()
    }

    {
        if(size==0)
            System.out.println("Deap empty");
        else
        {
            System.out.println("The deleted max elt:"+ h[3]);
            int i;
            int p=size+1;
            int t=h[p];
            size--;
            int big;
            for( i=3;2*i<=size+1;i=big)
            {
                if(h[rightchild(i)]>h[leftchild(i)])
                   big=rightchild(i);
                else
                       big=leftchild(i);
                h[i]=h[big];
            }
             p=i;
             h[p]=t;
            for(i=2;i<=size+1;i++)
           {
             switch(MaxHeap(i))
             {
                case 1:
                    int partner=MinPartner(i);
                    if(h[partner]>h[i])
                    {
                        swap(i,partner);
                        MinInsert(partner);
                    }
                    else
                       MaxInsert(i);
                    break;
                case 0:
                    partner=MaxPartner(i);
                    if(h[partner]<h[i])
                    {
                        swap(i,partner);
                        MaxInsert(partner);
                    }
                    else
                       MinInsert(i);
                    break;
               default:
                    System.out.println("ERROR");
               }
          }
        }
    }

public class deaps
}

{
                                                                10
public static void main(String args[]) throws IOException
    {
      int ch=0,cont=0;
      deapsalg h1=new deapsalg();
      do
      {
         System.out.println("DEAPs 1.Insert 2.Delete Min 3.Delete Max");
         DataInputStream din=new DataInputStream(System.in);
         try
         {
           ch=Integer.parseInt(din.readLine());
         }
         catch(Exception e){}
         if(ch==1)
         {
           h1.insert();
           h1.display();
         }
         else if(ch==2)
         {
            h1.deletemin();
            h1.display();
         }
         else if(ch==3)
         {
            h1.deletemax();
            h1.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);
    }
}




                                                             11
OUTPUT:
--------

DEAPs 1.Insert 2.Delete Min 3.Delete Max
1
Enter the element:
20
The deaps elements are:
0
20
press 1 to continue:
1
DEAPs 1.Insert 2.Delete Min 3.Delete Max
1
Enter the element:
5
The deaps elements are:
0
5
20
press 1 to continue:
1
DEAPs 1.Insert 2.Delete Min 3.Delete Max
1
Enter the element:
3
The deaps elements are:
0
3
20
5
press 1 to continue:
1
DEAPs 1.Insert 2.Delete Min 3.Delete Max
1
Enter the element:
7
The deaps elements are:
0
3
20
5
7
press 1 to continue:
1
DEAPs 1.Insert 2.Delete Min 3.Delete Max
1
Enter the element:
11



The deaps elements are:
0
3
20
5
7
11
press 1 to continue:
1




                                           12
DEAPs 1.Insert 2.Delete Min 3.Delete Max
1
Enter the element:
55
The deaps elements are:
0
3
55
5
7
11
20
press 1 to continue:
1
DEAPs 1.Insert 2.Delete Min 3.Delete Max
1
Enter the element:
77
The deaps elements are:
0
3
77
5
7
55
20
11
press 1 to continue:
1
DEAPs 1.Insert 2.Delete Min 3.Delete Max
1
Enter the element:
88
The deaps elements are:
0
3
88
5
7
77
20
11
55
press 1 to continue:
1
DEAPs 1.Insert 2.Delete Min 3.Delete Max
1

Enter the element:
17
The deaps elements are:
0
3
88
5
7
77
20
11
55




                                           13
17
press 1 to continue:
1
DEAPs 1.Insert 2.Delete Min 3.Delete Max
1
Enter the element:
1
The deaps elements are:
0
1
88
5
3
77
20
11
55
17
7
press 1 to continue:
1
DEAPs 1.Insert 2.Delete Min 3.Delete Max
1
Enter the element:
100
The deaps elements are:
0
1
100
5
3
88
20
11
55
17
7
77



press 1 to continue:
1
DEAPs 1.Insert 2.Delete Min 3.Delete Max
2
The deleted min elt:1
The deaps elements are:
0
3
100
5
7
88
77
11
55
17
20
press 1 to continue:




                                           14
RESULT

Thus the program for Deaps using Java has been implemented.




                                                  15
Ex.No:3
                                             LEFTIST HEAP
Date:




AIM

          To implement the leftist heap with insert and deletemin operation using Java.




ALGORITHM

   Step 1:        Start the program by defining function.

   Step 2:        We know heap as the root node with minimum element.

   Step 3:        The insert and delete operations are performed with the help of combining 2
                  trees.

   Step 4:        The insert operation is performed by combining the two leftist trees.

   Step 5:        The deletemin() is used to delete the minimum element in the heap.

   Step 6:        After the insert and delete operations leftist heap elements are displayed.

   Step 7:        Stop the program.




                                                        16
PROGRAM
LEFTIST HEAP
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;
                     }
                     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()
          {




                                                             17
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+" "+"SHORTEST "+currentnode.shortest);
        dispin(currentnode.RC);
         }
      }

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


                                                             18
}while(cont==1);
  }

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




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




                                   20
RESULT

Thus the program for leftist heap using Java has been implemented.




                                                    21
Ex no: 4
                                                  AVL TREE
Date:




AIM

           To implement the AVL tree with insert & delete operations using Java.

ALGORITHM

    Step 1:        Start the program by defining the functions.

    Step 2:        Insert the elements to the AVL tree.

    Step 3:        Check the tree if it is balanced or not.

    Step 4:        The balance factor is one of 0, 1 and -1.

    Step 5:        If it is not balanced, balance the tree using
                         (i)    Left-left
                         (ii) Left-right
                         (iii) Right-left
                         (iv)    Right-right
                   Balancing

    Step 6:        And if the tree is balanced and then the insert() and the delete() operations are
                   performed.

    Step 7:        Stop the program.




                                                          22
PROGRAM
AVL TREE
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){}
                        if(root==null)
                        {
               node y=new node();
                             y.data=newelt;
               y.bf=0;
                             y.LC=null;
                             y.RC=null;
                             root=y;
               return true;
                  }
                        node f,a,q,p;
         node b,c;
                        int d;
                        node y=new node();
                        boolean found, unbalanced;
                        f=null;
                        a=root;
                        p=root;
                        q=null;
                        found=false;
                        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;}
                        }
                        if(found==false)
             {
                             y.data=newelt;
               y.bf=0;
                             y.LC=null;
                          y.RC=null;
              if(newelt<q.data)
                                   q.LC=y;
              else




                                                               23
q.RC=y;
     if(newelt >a.data)
                          {p=a.RC;b=p;d=-1;}
     else
                          {p=a.LC;b=p;d=1;}
     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)
{
        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");




                                                         24
a.RC=b.LC;
                                       b.LC=a;
                                       a.bf=0;
                                       b.bf=0;
                             }
                             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;
        }
   return true;
  }
  return false;
 }
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+"       "+"BF "+currentnode.bf);
           dispin(currentnode.RC);




                                                               25
}
    }

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




                                                         26
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:
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




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




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




                       29
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
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
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
                       30
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
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




                       31
RESULT

Thus the program for AVL tree using Java has been implemented




                                                  32
Ex.No:5
                                                     B-TREE
Date:


AIM

          To implement the b-tree with insert and delete operations using Java.

ALGORITHM

            Step 1:        Start the program by defining function.

            Step 2:        Declare the class btree

            Step 3:        The insert and delete operations are performed

            Step 4:        To insert, check if root is empty, if it is empty
                           insert the element as root.

            Step 5:        If it is greater insert it into right sub tree.

            Step 6:        Otherwise, insert it into left sub tree

            Step 7:        Use the function split, to split the nodes

            Step 8:        Call the function display to display
                           data1,data2,address and parent

            Step 9:        End of the program




                                                           33
PROGRAM
B-TREE
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)
                        {
                              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




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


                                                          35
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);
                 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
      {




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




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




                                                           38
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




RESULT:
                   Thus the program for b-tree using Java has been implemented.




                                                            39
Ex no: 6
                                                        TRIES
Date:


AIM

           To implement the tries with insert & delete operations using Java.


ALGORITHM

    Step 1:        Start the program by defining the functions.

    Step 2:         First initialize the node to null

    Step 3:        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

    Step 4:        to insert the particular element read that elemnt and
                   insert the element with tag as 0 and level as 1.

    Step 5:        to display the elements ,display if root as null, print as
                   empty, otherwise call empty

    Step 6:        print the current node in left sub tre in the format as currentnode.data + level
                   and tag.

    Step 7:        display current node in the right sub tree

    Step 8:        end of the program




                                                           40
PROGRAM
TRIES
import java.io.*;
class node
{
       public int tag,level;
   starts with 1
   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());
            }
            catch(Exception e){}

                  if(root==null)
                  {
                            root=new node();




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




                                           42
temp.RC=n1;
                                                             n1.level=n2.level=temp.level+1;

                                                  n1.par=temp;
                                                  }
                                        }
                                        else      n2.par=temp;
                                        {
                                                  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;
                                        }

                              }

                  System.out.println("Element already exists");
                else

                    }

         public void display()
         }

         {
                     if(root==null)
              System.out.println("EMPTY");
            else
            {
                         System.out.println("nIn Order");
                         dispin(root);
            }
          }
    public void dispin(node currentnode)
     {
                                                                                         "+currentnode.level+"
         if(currentnode!=null)
         {
             dispin(currentnode.LC);
                          System.out.println(currentnode.data+"    "+"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());           43
         }
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);
    }
}




                                                             44
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
0     LEVEL- 3         TAG-1
1015
In Order LEVEL- 4
TAG-0 LEVEL- 3
1232
press 1
TAG-0 to continue:
1
0     LEVEL- 2         TAG-1
TRIES 1. Insert
1
Enter the element:
                               45
1942
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
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
                             46
In Order
1232     LEVEL- 3
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




RESULT

Thus the program for tries using Java has been implemented




                                                    47
Ex No: 7
                                                Quick Sort
Date:


AIM

        To write a Java program for the implementation the quick sort

ALGORITHM

        Step1   :start the program

        Step2: declare and initialize the array size

        Step3: enter the number of elements to be quick sorted.

        Step4: enter the elements using for loop

        Step5: call the function quick(1,noe)
               Void quick(int first,int last)

        Step6: if the first element is less than the last
               (a) then the first element is taken as the pivot &i=first, &j=last
               (b) the condition is checked for i<j if true

        Step7: set a loop to check the elements
               (a)while (a[pivot]>=a[i]&&i<last)i++;
               (b)while (a[pivot]>=a[j]&&j>first)j--;

        Step8: if (i>j)
               Swap(i,j)

        Step9: sort the elements and display the sorted values.




                                                       48
PROGRAM
Quick Sort
import java.io.*;
class quicksortalg
{
   int noe;
   int[] a=new int[100];
    public void sort()
   {
           try
           {
                   System.out.println("Enter the number of elements:");
                   DataInputStream din=new DataInputStream(System.in);
                   noe=Integer.parseInt(din.readLine());
                  System.out.println("Enter the elements:");
                  for(int i=1;i<=noe;i++)
                  a[i]=Integer.parseInt(din.readLine());
                   System.out.println("The array:");
                 display();
           }
           catch(Exception e){}
           quick(1,noe);
  }
   public void swap(int i,int j)
  {
     int t;
     t=a[i];a[i]=a[j];a[j]=t;
  }
 public void quick(int first,int last)
  {
    if(first<last)
    {
      int pivot=first;
      int i=first;
      int j=last;
      while(i<j)
      {
         while(a[pivot]>=a[i] && i<last) i++;
         while(a[pivot]<=a[j] && j>first) j--;
         if(i<j) swap(i,j);
       }
      swap(pivot,j);
      quick(first,j-1);
      quick(j+1,last);
    }
  }
   public void display()
   {
     for(int i=1;i<=noe;i++)



                                                      49
System.out.println(a[i]+"n");
    }

class quicksort
}

{
    public static void main(String args[])throws IOException
    {
      quicksortalg q1=new quicksortalg();
      q1.sort();
      System.out.println("The sorted array:");
      q1.display();
    }




                                                      50
OUTPUT
Enter the number of elements:
5
Enter the elements:
2
96
1
45
63
The array:
2
96
1
45
63

The sorted array:
1
2
45
63
96




RESULT:

            Thus the program for quick sort has been implemented using Java and the output is
verified.




                                                        51
Ex No: 8
                                           CONVEX HULL
Date:


AIM

        To write a Java program for the implementation of 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

                Step8: The function check id used to check whether the point is angular or
                       not(180▫)

                Step9: End of the program




                                                      52
PROGRAM
CONVEX HULL
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)
      {
             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]+")");

     }



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




                                                                54
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)




RESULT:

                  Thus the program for convex hull has been implemented using Java and the
output is verified.




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




AIM

       To write a Java program for the implementation of 0/1 knapsack using dynamic
programming.

ALGORITHM

    Step 1:     Start the program and define the function.

    Step 2:     Initialize the weight and profit.

    Step 3:     Read the number of objects that are given.

    Step 4:     For each objects, print the profit and weight

    Step 5:     Initializing is set to false.

    Step 6:     Display and print the item weight and profit

    Step 7:     Display the total cost

    Step 8:     End of the program.




                                                     56
PROGRAM
0/1 KNAPSACK USING DYNAMIC PROGRAMMING
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());
      }
      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+" tt "+st[n].profit);
      System.out.println("n Total profit:"+prof);       }}




                                                                  57
OUTPUT:
------

Enter the number of objects:
3
Enter the maximum weight sack can take:
10

For object 1
Enter profit: 20
Enter Weight: 6

For object 2
Enter profit: 10
Enter Weight: 2

For object 3
Enter profit: 19
Enter Weight: 3

The optimal solution is:
Item     weight          profit
1      6           20
3      3           19

Total profit:39




RESULT

                     Thus the program for 0/1 knapsack using Java has been implemented.




                                                       58
Ex No: 10
                      GRAPH COLORING USING BACKTRACKING
Date:


AIM

        To write the Java program for the implementation of graph coloring

ALGORITHM

   Step 1:      Start the program and define the function

   Step 2:      Create a class coloring

   Step 3:      Get the number of vertices in the graph

   Step 4:      Enter one if there is an edge in the graph

   Step 5:      And enter zero if there is no edge in the graph.

   Step 6:      Get the adjacency matrix of the given values

   Step 7:      Perform all possible combinations that are given

   Step 8:      Display all the combination

   Step 9:      End of the program




                                                      59
PROGRAM
GRAPH COLORING USING BACKTRACKING
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 ");
     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)
  {




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

class Graphcoloring
}

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

 }
}




                                                             61
OUTPUT:
-------

Enter number of vertices in the graph
4
Enter 1 if there is an edge Otherwise 0
between 1 and 1
0
between 1 and 2
1
between 1 and 3
0
between 1 and 4
1
between 2 and 1
1
between 2 and 2
0
between 2 and 3
1
between 2 and 4
0
between 3 and 1
0
between 3 and 2
1
between 3 and 3
0
between 3 and 4
1
between 4 and 1
1
between 4 and 2
0
between 4 and 3
1
between 4 and 4
0
Given adjacency matrix is
0     1       0       1
1     0       1       0
0     1       0       1
1     0       1       0
All possible combinations for m = 2 are
1     2       1       2
2     1       2       1
All possible combinations for m = 3 are
1     2       1       2
1     2       1       3
1     2       3       2
1     3       1       2
1     3       1       3
1     3       2       3
2     1       2       1
2     1       2       3
2     1       3       1
2     3       1       3
2     3       2       1




                                          62
2    3    2    3
3    1    2    1
3    1    3    1
3    1    3    2
3    2    1    2
3    2    3    1
3    2    3    2




RESULT

Thus the program for graph coloring using Java has been implemented.




                                                   63

Contenu connexe

Tendances

関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
riue
 
mobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkelingmobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkeling
Devnology
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 

Tendances (20)

Groovy kind of test
Groovy kind of testGroovy kind of test
Groovy kind of test
 
Awt
AwtAwt
Awt
 
Mattbrenner
MattbrennerMattbrenner
Mattbrenner
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
Promise
PromisePromise
Promise
 
mobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkelingmobl: Een DSL voor mobiele applicatieontwikkeling
mobl: Een DSL voor mobiele applicatieontwikkeling
 
Rデバッグあれこれ
RデバッグあれこれRデバッグあれこれ
Rデバッグあれこれ
 
Rのスコープとフレームと環境と
Rのスコープとフレームと環境とRのスコープとフレームと環境と
Rのスコープとフレームと環境と
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
Property-based testing
Property-based testingProperty-based testing
Property-based testing
 
Numerical Methods with Computer Programming
Numerical Methods with Computer ProgrammingNumerical Methods with Computer Programming
Numerical Methods with Computer Programming
 
Python Programming: Data Structure
Python Programming: Data StructurePython Programming: Data Structure
Python Programming: Data Structure
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScript
 
The Ring programming language version 1.5.3 book - Part 78 of 184
The Ring programming language version 1.5.3 book - Part 78 of 184The Ring programming language version 1.5.3 book - Part 78 of 184
The Ring programming language version 1.5.3 book - Part 78 of 184
 
Ejemplo radio
Ejemplo radioEjemplo radio
Ejemplo radio
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
Dotnet 18
Dotnet 18Dotnet 18
Dotnet 18
 
Intro to OTP in Elixir
Intro to OTP in ElixirIntro to OTP in Elixir
Intro to OTP in Elixir
 
Practical
PracticalPractical
Practical
 

Similaire à Data structures lab

( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
aristogifts99
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
Mohamed Ahmed
 
Ejercicios de programacion
Ejercicios de programacionEjercicios de programacion
Ejercicios de programacion
Jeff Tu Pechito
 
DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++
mustkeem khan
 
I need help with two things. First Id like someone to check over m.pdf
I need help with two things. First Id like someone to check over m.pdfI need help with two things. First Id like someone to check over m.pdf
I need help with two things. First Id like someone to check over m.pdf
info998421
 
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfDoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
aathiauto
 
I am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdfI am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdf
seamusschwaabl99557
 

Similaire à Data structures lab (20)

Cpds lab
Cpds labCpds lab
Cpds lab
 
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
( PLEASE SHOW HOW TO IMPLEMENT THE DELETION FUNCTION )SAMPLE OUTPU.pdf
 
PRACTICAL COMPUTING
PRACTICAL COMPUTINGPRACTICAL COMPUTING
PRACTICAL COMPUTING
 
C questions
C questionsC questions
C questions
 
Cpp c++ 1
Cpp c++ 1Cpp c++ 1
Cpp c++ 1
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
Computer Programming- Lecture 4
Computer Programming- Lecture 4Computer Programming- Lecture 4
Computer Programming- Lecture 4
 
Pnno
PnnoPnno
Pnno
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better code
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C Programs
 
Ejercicios de programacion
Ejercicios de programacionEjercicios de programacion
Ejercicios de programacion
 
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
 
DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++DATA STRUCTURE USING C & C++
DATA STRUCTURE USING C & C++
 
DSU C&C++ Practical File Diploma
DSU C&C++ Practical File DiplomaDSU C&C++ Practical File Diploma
DSU C&C++ Practical File Diploma
 
Java binary subtraction
Java binary subtractionJava binary subtraction
Java binary subtraction
 
Heap
HeapHeap
Heap
 
Python lab manual all the experiments are available
Python lab manual all the experiments are availablePython lab manual all the experiments are available
Python lab manual all the experiments are available
 
I need help with two things. First Id like someone to check over m.pdf
I need help with two things. First Id like someone to check over m.pdfI need help with two things. First Id like someone to check over m.pdf
I need help with two things. First Id like someone to check over m.pdf
 
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfDoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
 
I am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdfI am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdf
 

Dernier

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Dernier (20)

Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 

Data structures lab

  • 1. Ex No: 1 MIN HEAP Date: AIM To implement the min heap structure with insert and delete minimum operation using Java program ALGORITHM Step 1: start the program by creating function with min heap property Step 2: two functions namely insert() and deletemin() are created Step 3: The insert () is used to insert new element in the tree structure with heap property. Step 4: The deletemin() is used to delete the minimum element which is usually a root node. Step 5: The two operations are performed satisfying heapness and completeness property. Step 6: End of the program. 1
  • 2. PROGRAM: MIN HEAP import java.io.*; class heapalg { int maxsize=100,size; int[] h=new int[maxsize]; public int leftchild(int i) { return 2*i; } public int rightchild(int i) { return 2*i + 1; } public int parent(int i) { return i/2; } public boolean isleaf(int i) { return ((i<=size) && (i>size/2)); } public void swap(int i,int j) { int t; t=h[i];h[i]=h[j];h[j]=t; } public void display() { System.out.println("The heap elements are:"+"n"); for(int i=1;i<=size;i++) System.out.println("n"+h[i]); } public void insert() { size++; if(size>maxsize) System.out.println("Heapfull"); else { try { System.out.println("Enter the element:"); DataInputStream din=new DataInputStream(System.in); h[size]=Integer.parseInt(din.readLine()); } catch(Exception e){} insertelt(size); } } public void insertelt(int i) { while ((h[parent(i)]>h[i])) { int par=parent(i); swap(par,i); i=par; 2
  • 3. } public void delete() } { if(size==0) System.out.println("Heapempty"); else { System.out.println("The deleted min elt:"+h[1]); h[1]=h[size--]; if(size!=0) percolate(1); } } public void percolate(int i) { while(!isleaf(i)) { int small=leftchild(i); if( (small<size)&& h[small] > h[small+1]) small+=1; if(h[small] < h[i]) swap(small,i); i=small; } } class minheap } { public static void main(String args[]) throws IOException { int ch=0,cont=0; heapalg h1=new heapalg(); do { System.out.println("MIN HEAP 1.Insert 2.Delete Min"); DataInputStream din=new DataInputStream(System.in); try { ch=Integer.parseInt(din.readLine()); } catch(Exception e){} if(ch==1) { h1.insert(); h1.display(); } else if(ch==2) { h1.delete(); h1.display(); } else { System.out.println("Enter the correct choice"); } System.out.println("press 1 to continue:"); try { cont=Integer.parseInt(din.readLine()); 3
  • 4. } catch(Exception e){} }while(cont==1); } } 4
  • 5. OUTPUT: -------- MIN HEAP 1.Insert 2.Delete Min 1 Enter the element: 42 The heap elements are: 42 press 1 to continue: 1 MIN HEAP 1.Insert 2.Delete Min 1 Enter the element: 3 The heap elements are: 3 42 press 1 to continue: 1 MIN HEAP 1.Insert 2.Delete Min 1 Enter the element: 86 The heap elements are: 3 42 86 press 1 to continue: 1 MIN HEAP 1.Insert 2.Delete Min 1 Enter the element: 2 The heap elements are: 2 3 86 42 press 1 to continue: 1 MIN HEAP 1.Insert 2.Delete Min 2 The deleted min elt:2 The heap elements are: 3 42 86 press 1 to continue: 12 . 5
  • 6. Ex No: 2 DEAPS Date: AIM To implement program for deaps structure with insert and delete operations using Java. ALGORITHM Step 1: Start the program by creating Deap Structure. Step 2: Perform insert and delete functions. Step 3: The insert() is done with 2 methods namely maxinsert() and mininsert(). Step 4: The delete() is done with 2 methods namely deletemax() and deletemin() Step 5: The leftChild and rightChild are compared and the appropriate element is placed in the root node. Step 6: After the insert and delete operation Deap elements are displayed. Step 7: Stop of the program. 6
  • 7. PROGRAM DEAPS import java.io.*; class deapsalg { int maxsize=100,size; int[] h=new int[maxsize+1]; public int leftchild(int i) { return 2*i; } public int rightchild(int i) { return 2*i + 1; } public int parent(int i) { return i/2; } public boolean isleaf(int i) { return ((i<=size) && (i>size/2)); } public void swap(int i,int j) { int t; t=h[i];h[i]=h[j];h[j]=t; } public void display() { System.out.println("The deaps elements are:"); for(int i=1;i<=size+1;i++) System.out.println("n"+h[i]); } public int MaxHeap(int i) { int t=i; while(t!=2 && t!=3) t=t/2; if(t==2) { return 0; } else { return 1; } } public int MinPartner(int p) { int powvalue=(int) ((Math.floor(Math.log(p)/Math.log(2)))-1); int partner=p-(int)(Math.pow(2,powvalue)); return partner; } public int MaxPartner(int p) { int powvalue=(int) ((Math.floor(Math.log(p)/Math.log(2)))-1); 7
  • 8. int partner=p+(int)(Math.pow(2,powvalue)); if(partner>size+1) partner/=2; return partner; public void MinInsert(int i) } { while (parent(i)!=1 && (h[parent(i)]>h[i])) { int par=parent(i); swap(par,i); i=par; } public void MaxInsert(int i) } { while (parent(i) !=1 && (h[parent(i)]<h[i])) { int par=parent(i); swap(par,i); i=par; } public void insert() } { int newelt=0; size++; if(size>maxsize) System.out.println("Deap full"); else { try { System.out.println("Enter the element:"); DataInputStream din=new DataInputStream(System.in); newelt=Integer.parseInt(din.readLine()); } catch(Exception e){} if(size==1) { h[2]=newelt; return; } int p=size+1; h[p]=newelt; switch(MaxHeap(p)) { case 1: int partner=MinPartner(p); if(h[partner]>h[p]) { swap(p,partner); MinInsert(partner); } else MaxInsert(p); break; case 0: 8 partner=MaxPartner(p);
  • 9. if(h[partner]<h[p]) { swap(p,partner); MaxInsert(partner); } else MinInsert(p); break; default: System.out.println("ERROR"); } } public void deletemin() } { if(size==0) System.out.println("Deap empty"); else { System.out.println("The deleted min elt:"+ h[2]); int i; int p=size+1; int t=h[p]; size--; int small; for( i=2;2*i<=size+1;i=small) { if(h[rightchild(i)]<h[leftchild(i)]) small=rightchild(i); else small=leftchild(i); h[i]=h[small]; } p=i; t h[p]=t; for(i=2;i<=size+1;i++) { switch(MaxHeap(i)) { case 1: int partner=MinPartner(i); if(h[partner]>h[i]) { swap(i,partner); MinInsert(partner); } else MaxInsert(i); break; case 0: partner=MaxPartner(i); if(h[partner]<h[i]) { swap(i,partner); MaxInsert(partner); } else MinInsert(i); break; default: 9
  • 10. System.out.println("ERROR"); } } } public void deletemax() } { if(size==0) System.out.println("Deap empty"); else { System.out.println("The deleted max elt:"+ h[3]); int i; int p=size+1; int t=h[p]; size--; int big; for( i=3;2*i<=size+1;i=big) { if(h[rightchild(i)]>h[leftchild(i)]) big=rightchild(i); else big=leftchild(i); h[i]=h[big]; } p=i; h[p]=t; for(i=2;i<=size+1;i++) { switch(MaxHeap(i)) { case 1: int partner=MinPartner(i); if(h[partner]>h[i]) { swap(i,partner); MinInsert(partner); } else MaxInsert(i); break; case 0: partner=MaxPartner(i); if(h[partner]<h[i]) { swap(i,partner); MaxInsert(partner); } else MinInsert(i); break; default: System.out.println("ERROR"); } } } } public class deaps } { 10
  • 11. public static void main(String args[]) throws IOException { int ch=0,cont=0; deapsalg h1=new deapsalg(); do { System.out.println("DEAPs 1.Insert 2.Delete Min 3.Delete Max"); DataInputStream din=new DataInputStream(System.in); try { ch=Integer.parseInt(din.readLine()); } catch(Exception e){} if(ch==1) { h1.insert(); h1.display(); } else if(ch==2) { h1.deletemin(); h1.display(); } else if(ch==3) { h1.deletemax(); h1.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); } } 11
  • 12. OUTPUT: -------- DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 20 The deaps elements are: 0 20 press 1 to continue: 1 DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 5 The deaps elements are: 0 5 20 press 1 to continue: 1 DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 3 The deaps elements are: 0 3 20 5 press 1 to continue: 1 DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 7 The deaps elements are: 0 3 20 5 7 press 1 to continue: 1 DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 11 The deaps elements are: 0 3 20 5 7 11 press 1 to continue: 1 12
  • 13. DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 55 The deaps elements are: 0 3 55 5 7 11 20 press 1 to continue: 1 DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 77 The deaps elements are: 0 3 77 5 7 55 20 11 press 1 to continue: 1 DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 88 The deaps elements are: 0 3 88 5 7 77 20 11 55 press 1 to continue: 1 DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 17 The deaps elements are: 0 3 88 5 7 77 20 11 55 13
  • 14. 17 press 1 to continue: 1 DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 1 The deaps elements are: 0 1 88 5 3 77 20 11 55 17 7 press 1 to continue: 1 DEAPs 1.Insert 2.Delete Min 3.Delete Max 1 Enter the element: 100 The deaps elements are: 0 1 100 5 3 88 20 11 55 17 7 77 press 1 to continue: 1 DEAPs 1.Insert 2.Delete Min 3.Delete Max 2 The deleted min elt:1 The deaps elements are: 0 3 100 5 7 88 77 11 55 17 20 press 1 to continue: 14
  • 15. RESULT Thus the program for Deaps using Java has been implemented. 15
  • 16. Ex.No:3 LEFTIST HEAP Date: AIM To implement the leftist heap with insert and deletemin operation using Java. ALGORITHM Step 1: Start the program by defining function. Step 2: We know heap as the root node with minimum element. Step 3: The insert and delete operations are performed with the help of combining 2 trees. Step 4: The insert operation is performed by combining the two leftist trees. Step 5: The deletemin() is used to delete the minimum element in the heap. Step 6: After the insert and delete operations leftist heap elements are displayed. Step 7: Stop the program. 16
  • 17. PROGRAM LEFTIST HEAP 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; } 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() { 17
  • 18. 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+" "+"SHORTEST "+currentnode.shortest); dispin(currentnode.RC); } } }; 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){} 18
  • 19. }while(cont==1); } 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 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: 19
  • 20. 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 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 20
  • 21. RESULT Thus the program for leftist heap using Java has been implemented. 21
  • 22. Ex no: 4 AVL TREE Date: AIM To implement the AVL tree with insert & delete operations using Java. ALGORITHM Step 1: Start the program by defining the functions. Step 2: Insert the elements to the AVL tree. Step 3: Check the tree if it is balanced or not. Step 4: The balance factor is one of 0, 1 and -1. Step 5: If it is not balanced, balance the tree using (i) Left-left (ii) Left-right (iii) Right-left (iv) Right-right Balancing Step 6: And if the tree is balanced and then the insert() and the delete() operations are performed. Step 7: Stop the program. 22
  • 23. PROGRAM AVL TREE 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){} if(root==null) { node y=new node(); y.data=newelt; y.bf=0; y.LC=null; y.RC=null; root=y; return true; } node f,a,q,p; node b,c; int d; node y=new node(); boolean found, unbalanced; f=null; a=root; p=root; q=null; found=false; 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;} } if(found==false) { y.data=newelt; y.bf=0; y.LC=null; y.RC=null; if(newelt<q.data) q.LC=y; else 23
  • 24. q.RC=y; if(newelt >a.data) {p=a.RC;b=p;d=-1;} else {p=a.LC;b=p;d=1;} 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) { 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"); 24
  • 25. a.RC=b.LC; b.LC=a; a.bf=0; b.bf=0; } 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; } return true; } return false; } 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+" "+"BF "+currentnode.bf); dispin(currentnode.RC); 25
  • 26. } } 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); } } 26
  • 27. 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: 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 27
  • 28. 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 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 28
  • 29. 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 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 29
  • 30. 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 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 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 30
  • 31. 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 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 31
  • 32. RESULT Thus the program for AVL tree using Java has been implemented 32
  • 33. Ex.No:5 B-TREE Date: AIM To implement the b-tree with insert and delete operations using Java. ALGORITHM Step 1: Start the program by defining function. Step 2: Declare the class btree Step 3: The insert and delete operations are performed Step 4: To insert, check if root is empty, if it is empty insert the element as root. Step 5: If it is greater insert it into right sub tree. Step 6: Otherwise, insert it into left sub tree Step 7: Use the function split, to split the nodes Step 8: Call the function display to display data1,data2,address and parent Step 9: End of the program 33
  • 34. PROGRAM B-TREE 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) { 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 34
  • 35. { 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(); 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; 35
  • 36. 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); 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 { 36
  • 37. 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); } } 37
  • 38. 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 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 38
  • 39. 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 RESULT: Thus the program for b-tree using Java has been implemented. 39
  • 40. Ex no: 6 TRIES Date: AIM To implement the tries with insert & delete operations using Java. ALGORITHM Step 1: Start the program by defining the functions. Step 2: First initialize the node to null Step 3: 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 Step 4: to insert the particular element read that elemnt and insert the element with tag as 0 and level as 1. Step 5: to display the elements ,display if root as null, print as empty, otherwise call empty Step 6: print the current node in left sub tre in the format as currentnode.data + level and tag. Step 7: display current node in the right sub tree Step 8: end of the program 40
  • 41. PROGRAM TRIES import java.io.*; class node { public int tag,level; starts with 1 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()); } catch(Exception e){} if(root==null) { root=new node(); 41
  • 42. 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; } 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; 42
  • 43. temp.RC=n1; n1.level=n2.level=temp.level+1; n1.par=temp; } } else n2.par=temp; { 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; } } System.out.println("Element already exists"); else } public void display() } { if(root==null) System.out.println("EMPTY"); else { System.out.println("nIn Order"); dispin(root); } } public void dispin(node currentnode) { "+currentnode.level+" if(currentnode!=null) { dispin(currentnode.LC); System.out.println(currentnode.data+" "+"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()); 43 }
  • 44. 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); } } 44
  • 45. 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 0 LEVEL- 3 TAG-1 1015 In Order LEVEL- 4 TAG-0 LEVEL- 3 1232 press 1 TAG-0 to continue: 1 0 LEVEL- 2 TAG-1 TRIES 1. Insert 1 Enter the element: 45 1942
  • 46. 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 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 46 In Order 1232 LEVEL- 3
  • 47. 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 RESULT Thus the program for tries using Java has been implemented 47
  • 48. Ex No: 7 Quick Sort Date: AIM To write a Java program for the implementation the quick sort ALGORITHM Step1 :start the program Step2: declare and initialize the array size Step3: enter the number of elements to be quick sorted. Step4: enter the elements using for loop Step5: call the function quick(1,noe) Void quick(int first,int last) Step6: if the first element is less than the last (a) then the first element is taken as the pivot &i=first, &j=last (b) the condition is checked for i<j if true Step7: set a loop to check the elements (a)while (a[pivot]>=a[i]&&i<last)i++; (b)while (a[pivot]>=a[j]&&j>first)j--; Step8: if (i>j) Swap(i,j) Step9: sort the elements and display the sorted values. 48
  • 49. PROGRAM Quick Sort import java.io.*; class quicksortalg { int noe; int[] a=new int[100]; public void sort() { try { System.out.println("Enter the number of elements:"); DataInputStream din=new DataInputStream(System.in); noe=Integer.parseInt(din.readLine()); System.out.println("Enter the elements:"); for(int i=1;i<=noe;i++) a[i]=Integer.parseInt(din.readLine()); System.out.println("The array:"); display(); } catch(Exception e){} quick(1,noe); } public void swap(int i,int j) { int t; t=a[i];a[i]=a[j];a[j]=t; } public void quick(int first,int last) { if(first<last) { int pivot=first; int i=first; int j=last; while(i<j) { while(a[pivot]>=a[i] && i<last) i++; while(a[pivot]<=a[j] && j>first) j--; if(i<j) swap(i,j); } swap(pivot,j); quick(first,j-1); quick(j+1,last); } } public void display() { for(int i=1;i<=noe;i++) 49
  • 50. System.out.println(a[i]+"n"); } class quicksort } { public static void main(String args[])throws IOException { quicksortalg q1=new quicksortalg(); q1.sort(); System.out.println("The sorted array:"); q1.display(); } 50
  • 51. OUTPUT Enter the number of elements: 5 Enter the elements: 2 96 1 45 63 The array: 2 96 1 45 63 The sorted array: 1 2 45 63 96 RESULT: Thus the program for quick sort has been implemented using Java and the output is verified. 51
  • 52. Ex No: 8 CONVEX HULL Date: AIM To write a Java program for the implementation of 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 Step8: The function check id used to check whether the point is angular or not(180▫) Step9: End of the program 52
  • 53. PROGRAM CONVEX HULL 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) { 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]+")"); } 53
  • 54. 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])) { 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(); } 54
  • 55. 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) RESULT: Thus the program for convex hull has been implemented using Java and the output is verified. 55
  • 56. Ex No: 9 0/1 KNAPSACK USING DYNAMIC PROGRAMMING Date: AIM To write a Java program for the implementation of 0/1 knapsack using dynamic programming. ALGORITHM Step 1: Start the program and define the function. Step 2: Initialize the weight and profit. Step 3: Read the number of objects that are given. Step 4: For each objects, print the profit and weight Step 5: Initializing is set to false. Step 6: Display and print the item weight and profit Step 7: Display the total cost Step 8: End of the program. 56
  • 57. PROGRAM 0/1 KNAPSACK USING DYNAMIC PROGRAMMING 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()); } 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+" tt "+st[n].profit); System.out.println("n Total profit:"+prof); }} 57
  • 58. OUTPUT: ------ Enter the number of objects: 3 Enter the maximum weight sack can take: 10 For object 1 Enter profit: 20 Enter Weight: 6 For object 2 Enter profit: 10 Enter Weight: 2 For object 3 Enter profit: 19 Enter Weight: 3 The optimal solution is: Item weight profit 1 6 20 3 3 19 Total profit:39 RESULT Thus the program for 0/1 knapsack using Java has been implemented. 58
  • 59. Ex No: 10 GRAPH COLORING USING BACKTRACKING Date: AIM To write the Java program for the implementation of graph coloring ALGORITHM Step 1: Start the program and define the function Step 2: Create a class coloring Step 3: Get the number of vertices in the graph Step 4: Enter one if there is an edge in the graph Step 5: And enter zero if there is no edge in the graph. Step 6: Get the adjacency matrix of the given values Step 7: Perform all possible combinations that are given Step 8: Display all the combination Step 9: End of the program 59
  • 60. PROGRAM GRAPH COLORING USING BACKTRACKING 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 "); 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) { 60
  • 61. 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); } class Graphcoloring } { public static void main(String args[ ])throws IOException { gcoloring g=new gcoloring(); g.read(); } } 61
  • 62. OUTPUT: ------- Enter number of vertices in the graph 4 Enter 1 if there is an edge Otherwise 0 between 1 and 1 0 between 1 and 2 1 between 1 and 3 0 between 1 and 4 1 between 2 and 1 1 between 2 and 2 0 between 2 and 3 1 between 2 and 4 0 between 3 and 1 0 between 3 and 2 1 between 3 and 3 0 between 3 and 4 1 between 4 and 1 1 between 4 and 2 0 between 4 and 3 1 between 4 and 4 0 Given adjacency matrix is 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 All possible combinations for m = 2 are 1 2 1 2 2 1 2 1 All possible combinations for m = 3 are 1 2 1 2 1 2 1 3 1 2 3 2 1 3 1 2 1 3 1 3 1 3 2 3 2 1 2 1 2 1 2 3 2 1 3 1 2 3 1 3 2 3 2 1 62
  • 63. 2 3 2 3 3 1 2 1 3 1 3 1 3 1 3 2 3 2 1 2 3 2 3 1 3 2 3 2 RESULT Thus the program for graph coloring using Java has been implemented. 63