This is the program to extract the minimum element from a min heap and restore the heap property among the remaining elements...
/**
*
* @author Akshay Ratan(ARC)
*/
import java.io.*;
public class MinHeap {
static int smallest;
static int n;
// static int arr2[]=new int[444];
//static int j=0;
public static void main(String args[])throws IOException
{
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of elements ..press enter and then enter number of elements");
int arr[]=new int[444];
n=Integer.parseInt(obj.readLine());
for(int i=1;i<=n;i++){
arr[i]=Integer.parseInt(obj.readLine());
}
BuildHeap(arr);
for(int k=1;k<=n;k++)
System.out.print(arr[k]+" ");
System.out.println("Minimum element in the heap is"+" "+arr[1]);
System.out.println("see the new min-heap!!");
/*String y=obj.readLine();
if(y=="Y"||y=="y"){*/
HeapMinExtract(arr);
BuildHeap(arr);
for(int k=1;k<=n;k++)
System.out.print(arr[k]+" ");
}
public static void MinHeapify(int arr[],int i)
{
int l=2*i;
int r=(2*i)+1;
if(l<=n && arr[l]<arr[i])
smallest=l;
else smallest=i;
if(r<=n && arr[r]<arr[smallest])
{
smallest=r;
}
int t;
if(smallest!=i)
{
t=arr[i];
arr[i]=arr[smallest];
arr[smallest]=t;
}
}
static void BuildHeap(int arr[])
{
double f=Math.floor(n/2);
for(int i=(int)f;i>=1;i--)
{
MinHeapify(arr,i);
}
}
static void HeapMinExtract(int arr[])
{
if(n<1)
System.out.println("Heap underflow !!");
else{
int min;
min=arr[1];
arr[1]=arr[n]; //exchange
n--;
MinHeapify(arr,1);
}
}
}







0 comments:
Post a Comment