forked from iRupam/NewtonSchoolInfinityJune21
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.java
More file actions
73 lines (59 loc) · 1.91 KB
/
MaxHeap.java
File metadata and controls
73 lines (59 loc) · 1.91 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
package InfinityJune21.Heap;
import java.util.Scanner;
public class MaxHeap {
private int heap[];
private int size;
private int maxSize;
public MaxHeap(int maxSize) {
this.maxSize = maxSize;
heap = new int[maxSize];
size = 0;
}
public void swap(int position1, int position2) {
int temp = heap[position1];
heap[position1] = heap[position2];
heap[position2] = temp;
}
public int parent(int position) {
return (position - 1) / 2;
}
public void insert(int element) {
heap[size] = element;
int current = size;
while(heap[current] > heap[parent(current)]) {
swap(current, parent(current));
current = parent(current);
}
size++;
}
public void print() {
System.out.println("Parent - Child:");
for(int i = 0; i <= (size / 2); i++) {
System.out.println("Parent: " + heap[i]);
System.out.println("Left Child: " + heap[2 * i + 1]);
System.out.println("Right Child: " + heap[2 * i + 2]);
System.out.println();
}
}
public void printArray() {
System.out.println("Array: ");
for(int i = 0; i < size; i++) {
System.out.print(heap[i] + " ");
}
System.out.println();
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
MaxHeap maxHeap = new MaxHeap(20);
System.out.print("Enter size of heap: ");
int size = scanner.nextInt();
for(int i = 0; i < size; i++) {
System.out.print("Enter value of the element to insert: ");
int element = scanner.nextInt();
maxHeap.insert(element);
}
maxHeap.printArray();
maxHeap.print();
}
}