Skip to content

Instantly share code, notes, and snippets.

@rishi93
Last active November 2, 2015 05:01
Show Gist options
  • Save rishi93/86b157bf126a63c6b770 to your computer and use it in GitHub Desktop.
Save rishi93/86b157bf126a63c6b770 to your computer and use it in GitHub Desktop.
Simple Binary Minimum Heap Implementation Using Arrays
import java.io.*;
public class Main
{
static void swapElements(int[] arr,int i,int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void printarray(int[] arr)
{
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]);
System.out.print(" ");
}
System.out.println();
}
static void insert(int[] arr, int elem)
{
int last = 0,parent,temp;
for(int i = 1; i < arr.length; i++)
{
if(arr[i] == 0)
{
arr[i] = elem;
last = i;
break;
}
}
while(last > 1)
{
parent = last/2;
if(arr[parent] > arr[last])
{
swapElements(arr,parent,last);
last = parent;
}
else
{
break;
}
}
}
static void deleteMin(int[] arr)
{
int last = 0,curr = 1,temp;
for(int i = 1; i < arr.length; i++)
{
if(arr[i] == 0)
{
last = i - 1;
break;
}
}
arr[1] = arr[last];
arr[last] = 0;
while(curr < last)
{
int left_child = 2*curr;
int right_child = 2*curr+1;
if((arr[curr] > arr[left_child] && arr[left_child] != 0)|| (arr[curr] > arr[right_child] && arr[right_child] != 0))
{
if(arr[left_child] < arr[right_child])
{
swapElements(arr,curr,left_child);
curr = left_child;
}
else
{
swapElements(arr,curr,right_child);
curr = right_child;
}
}
else
{
break;
}
}
}
public static void main(String args[])
{
int[] arr = new int[10];
arr[1] = 6;
arr[2] = 7;
arr[3] = 12;
arr[4] = 10;
arr[5] = 15;
arr[6] = 17;
System.out.println("Original Tree");
printarray(arr);
System.out.println("Inserting 5");
insert(arr,5);
printarray(arr);
System.out.println("Inserting 11");
insert(arr,11);
printarray(arr);
System.out.println("Delete Min");
deleteMin(arr);
printarray(arr);
System.out.println("Delete Min");
deleteMin(arr);
printarray(arr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment