-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeletionMinHeap.java
More file actions
50 lines (41 loc) · 1.18 KB
/
DeletionMinHeap.java
File metadata and controls
50 lines (41 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package Heaps;
import java.util.ArrayList;
import java.util.List;
/*
* 1) Swap first and last.
* 2) Delete last element.
* 3) Push down till correct position.
* */
public class DeletionMinHeap {
public static void delete(List<Integer> heap) {
Basics.swap(heap, 0, heap.size() - 1);
heap.remove(heap.size() - 1);
pushDown(heap, 0, heap.size() - 1);
}
public static void pushDown(List<Integer> heap, int i, int n) {
if (i == n) return;
int left = (2 * i) + 1;
int right = (2 * i) + 2;
int smallest = i;
if (left <= n && heap.get(left) < heap.get(smallest)) {
smallest = left;
}
if (right <= n && heap.get(right) < heap.get(smallest)) {
smallest = right;
}
if (smallest == i) return;
Basics.swap(heap, i, smallest);
pushDown(heap, smallest, n);
}
public static void main(String[] args) {
List<Integer> heap = new ArrayList<>();
heap.add(10);
heap.add(20);
heap.add(30);
heap.add(40);
heap.add(50);
System.out.println(heap);
delete(heap);
System.out.println(heap);
}
}