-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.java
More file actions
101 lines (67 loc) · 1.73 KB
/
Heap.java
File metadata and controls
101 lines (67 loc) · 1.73 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
91
92
93
94
95
96
97
98
99
100
101
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Heap {
public void heapyfy(ArrayList<Integer> array, int i) {
int size = array.size();
int largest = i;
int left = 2*i+1;
int right = 2*i+2;
if(left < size && array.get(left) > array.get(largest)) {
largest = left;
}
if(right< size && array.get(right) > array.get(largest)) {
largest = right;
}
if(largest != i ) {
int temp = array.get(i);
array.set(i,array.get(largest));
array.set(largest, temp);
heapyfy(array,largest);
}
}
public void insertNode(ArrayList<Integer> array , int newNum) {
if(array.size() == 0) {
array.add(newNum);
}else {
array.add(newNum);
for(int i = (array.size()/2) -1 ; i>=0 ; i--) {
heapyfy(array,i);
}
}
}
public void deleteNode(ArrayList<Integer> array , int num) {
int i=0;
int size = array.size();
for(i = 0 ; i < size ; i ++) {
if(array.get(i) == num ) {
break;
}
}
int temp = array.get(i);
array.set(i, array.get(size-1));
array.set(size-1, temp);
array.remove(size-1);
for(int j= size/2-1 ; j >= 0 ; j--) {
heapyfy(array,i);
}
}
public void printArray(ArrayList<Integer> array) {
for(int n : array) {
System.out.print(n+" ");
}
}
public static void main(String args[]) {
ArrayList<Integer> array = new ArrayList<Integer>();
Heap h = new Heap();
Queue<Integer> q = new LinkedList<Integer>();
h.insertNode(array, 3);
h.insertNode(array, 4);
h.insertNode(array, 9);
h.insertNode(array, 5);
h.insertNode(array, 2);
h.printArray(array);
h.deleteNode(array,9);
h.printArray(array);
}
}