-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeaps.java
More file actions
90 lines (80 loc) · 2.39 KB
/
Heaps.java
File metadata and controls
90 lines (80 loc) · 2.39 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
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
package dsa;
public class Heaps {
private int [] items = new int[10];
private int size;
public void insert(int value){
if (isTreeFull()) throw new IllegalStateException();
items[size++] = value;
bubbleup();
}
private void bubbleup(){
var index = size - 1;
while (index > 0 && items[index] > items[parent(index)]){
swap(index, parent(index));
index = parent(index);
}
}
public int remove(){
if (isEmpty()) throw new IllegalStateException();
var root = items[0];
items[0] = items[--size];
bubbledown();
return root;
}
public boolean isEmpty(){
return size == 0;
}
public int max(){
return items[0];
}
private void bubbledown(){
var index = 0;
while (index <= size && !isValidParent(index)){
var largerChildIndex = largerChildIndex(index);
swap(index, largerChildIndex);
index = largerChildIndex;
}
}
private void swap(int first, int second) {
var temp = items[first];
items[first] = items[second];
items[second] = temp;
}
private int largerChildIndex(int index){
if(!hasLeftChild(index)) return index;
if(!hasRightChild(index)) return largerChildIndex(index);
return leftChild(index) > rightChild(index) ?
leftChildIndex(index) : rightChildIndex(index);
}
private boolean hasLeftChild(int index){
return leftChildIndex(index) <= size;
}
private boolean hasRightChild(int index){
return rightChildIndex(index) <= size;
}
private boolean isValidParent(int index){
if(!hasLeftChild(index)) return true;
var isValid = items[index] >= leftChild(index);
if(hasRightChild(index))
isValid &= items[index] >= rightChild(index);
return isValid;
}
private int leftChild(int index){
return items[leftChildIndex(index)];
}
private int rightChild(int index){
return items[rightChildIndex(index)];
}
private int leftChildIndex(int index){
return (index * 2) + 1;
}
private int rightChildIndex(int index){
return (index * 2) + 2;
}
private boolean isTreeFull(){
return size == items.length;
}
private int parent(int index){
return (index - 1)/ 2;
}
}