File tree Expand file tree Collapse file tree 6 files changed +33
-63
lines changed
out/production/Crux/com/company
src/com/company/Lecture19 Expand file tree Collapse file tree 6 files changed +33
-63
lines changed Original file line number Diff line number Diff line change @@ -19,57 +19,56 @@ private int parent(int index){
19
19
20
20
public void add (T value ){
21
21
list .add (value );
22
-
23
- upheap (list .size () - 1 );
22
+ upHeap (list .size () - 1 );
24
23
}
25
24
26
- private void upheap (int index ){
25
+ private void upHeap (int index ){
27
26
if (index == 0 ){
28
27
return ;
29
28
}
30
-
31
29
int parent = parent (index );
32
-
33
30
if (list .get (parent ).compareTo (list .get (index )) <= 0 ){
34
31
return ;
35
32
}
36
-
37
33
T temp = list .get (index );
38
34
list .set (index ,list .get (parent ));
39
35
list .set (parent ,temp );
40
-
41
- upheap (parent );
36
+ upHeap (parent );
42
37
}
43
38
44
- private void downheap (int index ){
39
+ private void downHeap (int index ){
45
40
int min = index ;
46
-
47
41
int left = left (index );
48
42
int right = right (index );
49
-
50
43
if (left < list .size () && list .get (left ).compareTo (list .get (min )) < 0 ){
51
44
min = left ;
52
45
}
53
-
54
46
if (right < list .size () && list .get (right ).compareTo (list .get (min )) < 0 ){
55
47
min = right ;
56
48
}
57
-
58
- if (index != min ){
49
+ if (min != index ){
59
50
T temp = list .get (index );
60
51
list .set (index ,list .get (min ));
61
52
list .set (min ,temp );
53
+ downHeap (min );
62
54
}
63
55
}
64
56
65
57
public T remove (){
66
- T value = list .get (0 );
67
-
68
- if (list .size () > 1 ){
69
- list .set (0 ,list .remove (list .size ()-1 ));
70
- downheap (0 );
58
+ if (list .isEmpty ()) {
59
+ return null ;
71
60
}
72
-
61
+ if (list .size () == 1 ) {
62
+ return list .remove (0 );
63
+ }
64
+ T value = list .get (0 );
65
+ list .set (0 ,list .remove (list .size ()-1 ));
66
+ downHeap (0 );
73
67
return value ;
74
68
}
69
+
70
+ @ Override
71
+ public String toString () {
72
+ return list .toString ();
73
+ }
75
74
}
Original file line number Diff line number Diff line change 2
2
3
3
public class HeapClient {
4
4
public static void main (String [] args ) {
5
- Heap <Integer > heap = new Heap <Integer >();
5
+ Heap <Integer > heap = new Heap <>();
6
6
7
7
heap .add (4 );
8
8
heap .add (8 );
@@ -11,7 +11,9 @@ public static void main(String[] args) {
11
11
12
12
System .out .println (heap .remove ());
13
13
System .out .println (heap .remove ());
14
+ System .out .println (heap );
14
15
System .out .println (heap .remove ());
15
16
System .out .println (heap .remove ());
17
+ System .out .println (heap );
16
18
}
17
19
}
You can’t perform that action at this time.
0 commit comments