Skip to content

Commit 89d7d33

Browse files
Create Heap.java
1 parent 3112594 commit 89d7d33

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

7 Priority Queues/Heap.java

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package Heaps;
2+
//Implementation of max heap with a dynamically expanding array
3+
public class Heap {
4+
private int[] arr;
5+
private int capacity;
6+
private int count;
7+
public Heap(int capacity){
8+
this.capacity = capacity;
9+
arr = new int[capacity];
10+
this.count = 0;
11+
}
12+
13+
//Given a node's index we need to return the parent's index
14+
//O(1)
15+
public int parent(int i){
16+
if(i==0){
17+
return -1;
18+
}
19+
else
20+
return (i-1)/2;
21+
}
22+
23+
//Given a node's index we need to return the index of the left child
24+
//O(1)
25+
public int leftChild(int i){
26+
if(2*i+1>=count) return -1;
27+
return 2*i+1;
28+
}
29+
30+
//Given a node's index we need to return the index of the right child
31+
//O(1)
32+
public int rightChild(int i){
33+
if(2*i+2>=count) return -1;
34+
return 2*i+2;
35+
}
36+
37+
//Get the max element in the heap
38+
//O(1)
39+
public int getMax(){
40+
return arr[0];
41+
}
42+
43+
//Heapifying an element
44+
//O(logn)
45+
public void perlocateDown(int i){
46+
int l = leftChild(i);
47+
int r = rightChild(i);
48+
int max = i;
49+
if(l!=-1 && arr[l]>arr[i]) max = l;
50+
if(r!=-1 && arr[r]>arr[max]) max = r;
51+
if(max!=i){
52+
swap(arr,i,max);
53+
perlocateDown(max);
54+
}
55+
}
56+
57+
public static void swap(int[] arr, int i, int j){
58+
int temp = arr[i];
59+
arr[i] = arr[j];
60+
arr[j] = temp;
61+
}
62+
63+
//O(logn)
64+
public void Insert(int val){
65+
if(this.count==this.capacity) expand();
66+
this.count++;
67+
int i = this.count-1;
68+
while(i>=0 && val>arr[(i-1)/2]){
69+
arr[i] = arr[(i-1)/2];
70+
i = (i-1)/2;
71+
}
72+
arr[i] = val;
73+
}
74+
75+
public void expand(){
76+
int[] newarr = new int[capacity<<1];
77+
for(int i=0;i<arr.length;i++){
78+
newarr[i] = arr[i];
79+
}
80+
arr = newarr;
81+
}
82+
83+
//O(logn)
84+
public int deleteMax(){
85+
if(this.count==0) return -1;
86+
int ret = arr[0];
87+
int last = arr[arr.length-1];
88+
this.arr[0] = last;
89+
this.count--;
90+
perlocateDown(0);
91+
return ret;
92+
}
93+
}

0 commit comments

Comments
 (0)