-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxheaps.java
More file actions
90 lines (76 loc) · 1.9 KB
/
Copy pathMaxheaps.java
File metadata and controls
90 lines (76 loc) · 1.9 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
class MaxHeap {
int[] heap;
int size;
int capacity;
MaxHeap(int capacity) {
this.capacity = capacity;
this.size = 0;
heap = new int[capacity];
}
void insert(int value) {
if (size == capacity) {
System.out.println("IT'S FULL");
return;
}
heap[size] = value;
heapifyUp(size);
size++;
}
void heapifyUp(int index) {
while (index > 0 && heap[index] > heap[(index - 1) / 2]) {
swap(index, (index - 1) / 2);
index = (index - 1) / 2;
}
}
int delete() {
if (size <= 0) return -1;
if (size == 1) {
size--;
return heap[0];
}
int root = heap[0];
heap[0] = heap[size - 1];
size--;
heapifyDown(0);
return root;
}
void heapifyDown(int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < size && heap[left] > heap[largest])
largest = left;
if (right < size && heap[right] > heap[largest])
largest = right;
if (largest != i) {
swap(i, largest);
heapifyDown(largest);
}
}
void swap(int i, int j) {
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
void display() {
for (int i = 0; i < size; i++) {
System.out.print(heap[i] + " ");
}
System.out.println();
}
}
public class Maxheaps {
public static void main(String[] args) {
MaxHeap h = new MaxHeap(10);
h.insert(4);
h.insert(5);
h.insert(3);
h.insert(10);
h.insert(40);
h.display();
h.delete();
h.display();
h.delete();
h.display();
}
}