-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeap.java
127 lines (101 loc) · 2.88 KB
/
Heap.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import java.util.ArrayList;
public class Heap {
ArrayList<Integer> arr = new ArrayList<Integer>();
String mode;
Heap(ArrayList<Integer> val, String type) {
arr = val;
mode = type;
arr = heapify(0);
}
Heap(int[] val, String type) {
mode = type;
for (int i : val) {
arr.add(i);
}
arr = heapify(0);
}
protected void insert(int val) {
arr.add(val);
arr = heapify(0);
}
protected void delete(int index) {
int last_index = arr.size() - 1;
arr.set(index, arr.get(last_index));
arr.remove(last_index);
arr = heapify(0);
}
protected int peek() {
return arr.get(0);
}
protected int extract() {
int root = peek();
delete(0);
return root;
}
private ArrayList<Integer> heapRecur(int index) {
int left = (2*index)+1;
int right = (2*index)+2;
int target = index;
int indexL = arr.size()-1;
if (left <= indexL) {
if (mode == "min") {
if (arr.get(left) < arr.get(target)) {
target = left;
}
} else {
if (arr.get(left) > arr.get(target)) {
target = left;
}
}
}
if (right <= indexL) {
if (mode == "min") {
if (arr.get(right) < arr.get(target)) {
target = right;
}
} else {
if (arr.get(right) > arr.get(target)) {
target = right;
}
}
}
if (arr.get(index) != arr.get(target)) {
int swap = arr.get(index);
arr.set(index, arr.get(target));
arr.set(target, swap);
if ((index%2 == 0) && (index > 0)) {
arr = heapRecur((index/2) - 1);
} else if (index%2 != 0) {
arr = heapRecur(index/2);
}
arr = heapRecur(target);
} else {
return arr;
}
return arr;
}
private ArrayList<Integer> heapify(int index) {
if (index > (arr.size()/2)-1) {
return arr;
}
if (mode == "min") {
arr = heapRecur(index);
} else {
arr = heapRecur(index);
}
return heapify(index+1);
}
public static void main(String[] args) {
// int[] arr = {1, 2, 3, 4, 10, 25, 30, 40, 1000, 5000};
int [] arr = {3, 56, 89, 1, 34, 1000, 1, 23};
Heap heap = new Heap(arr, "max");
// heap.insert(666);
// heap.insert(78);
// heap.delete(5);
// System.out.println(heap.peek());
// System.out.println(heap.extract());
for (int i : heap.arr) {
System.out.println(i);
}
}
}