Search This Blog

Thursday 22 January 2015

How to make Altenate Heap?

/*
Here is the Solution in java language. Code has two classes...
 1> Main
 2> AlternateHP 
 */

import java.util.Scanner;

public class Main {
    private static Scanner s;

    public static void main(String args[])throws Exception
    {       
        s = new Scanner(System.in);
        System.out.println("how many element u want to sort->");
        int n=Integer.parseInt(s.nextLine());
       
        int[] a=new int[n+1];
       
        System.out.println("eneter elements->");
        for(int i=1;i<=n;i++)
        {
            a[i]=Integer.parseInt(s.nextLine());
        }
        AlternateHP h=new AlternateHP(a);
       
        h.BuildHeap(a);
       
        for(int i=1;i<=n;i++)
        {
            System.out.println(a[i]);
        }
       
    }

}
 

public class AlternateHP {
   
    public static  int i=1;
    public int p;
    public static int q=0;
    public int heapsize;
    AlternateHP(int a[])
    {
       
        heapsize=a.length-1;
        p=heapsize/2;
    }

    public void BuildHeap(int[] a) {
        int row=1;
       
        while(i!=p+1)
        {
           
            if(row%2==1)
            {
                int c=1;
                while(c<=(int)Math.pow(2, row-1) && i<=p)
                {
                    //System.out.println("min");
                    this.MinHeapify(a, i);
                    i++;
                    c++;
                }
            }
            if(row%2==0)
            {
                int c=1;
                while(c<=(int)Math.pow(2, row-1) && i<=p)
                {
                    //System.out.println("max");
                    this.MaxHeapify(a, i);
                    i++;
                    c++;
                }
            }
            row++;
        }
       
    }
    public void MaxHeapify(int[] a,int i)
    {
       
        int largest;
        int l=(2*i);
        int r=(2*i)+1;

        if(l<=heapsize && a[l]>a[i])
        {
        largest=l;
        }
        else
        {
            largest=i;
        }
        if(r<=heapsize && a[r]>a[largest])
        {
            largest=r;
        }
        if(largest!=i)
        {
            int temp=a[i];
            a[i]=a[largest];
            a[largest]=temp;
        }
    }
    public void MinHeapify(int[] a,int i)
    {
       
        int smallest;
        int l=(2*i);
        int r=(2*i)+1;

        if(l<=heapsize && a[i]>a[l])
        {
             smallest=l;
        }
        else
        {
             smallest=i;
        }
        if(r<=heapsize && a[r]<a[ smallest])
        {
             smallest=r;
        }
        if( smallest!=i)
        {
            int temp=a[i];
            a[i]=a[ smallest];
            a[ smallest]=temp;
        }
    }
    public void swap(int[] a,int p, int q)
    {
        int t=a[p];
        a[p]=a[q];
        a[q]=t;
    }
   
}

No comments:

Post a Comment

Blog Archive