Skip to content

Commit d689184

Browse files
committed
updated heap
1 parent 20d50c2 commit d689184

File tree

6 files changed

+33
-63
lines changed

6 files changed

+33
-63
lines changed

.idea/workspace.xml

Lines changed: 11 additions & 42 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Binary file not shown.
Binary file not shown.
Binary file not shown.

src/com/company/Lecture19/Heap.java

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -19,57 +19,56 @@ private int parent(int index){
1919

2020
public void add(T value){
2121
list.add(value);
22-
23-
upheap(list.size() - 1);
22+
upHeap(list.size() - 1);
2423
}
2524

26-
private void upheap(int index){
25+
private void upHeap(int index){
2726
if(index == 0){
2827
return;
2928
}
30-
3129
int parent = parent(index);
32-
3330
if(list.get(parent).compareTo(list.get(index)) <= 0){
3431
return;
3532
}
36-
3733
T temp = list.get(index);
3834
list.set(index,list.get(parent));
3935
list.set(parent,temp);
40-
41-
upheap(parent);
36+
upHeap(parent);
4237
}
4338

44-
private void downheap(int index){
39+
private void downHeap(int index){
4540
int min = index;
46-
4741
int left = left(index);
4842
int right = right(index);
49-
5043
if(left < list.size() && list.get(left).compareTo(list.get(min)) < 0){
5144
min = left;
5245
}
53-
5446
if(right < list.size() && list.get(right).compareTo(list.get(min)) < 0 ){
5547
min = right;
5648
}
57-
58-
if(index != min){
49+
if(min != index){
5950
T temp = list.get(index);
6051
list.set(index,list.get(min));
6152
list.set(min,temp);
53+
downHeap(min);
6254
}
6355
}
6456

6557
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;
7160
}
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);
7367
return value;
7468
}
69+
70+
@Override
71+
public String toString() {
72+
return list.toString();
73+
}
7574
}

src/com/company/Lecture19/HeapClient.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
public class HeapClient {
44
public static void main(String[] args) {
5-
Heap<Integer> heap = new Heap<Integer>();
5+
Heap<Integer> heap = new Heap<>();
66

77
heap.add(4);
88
heap.add(8);
@@ -11,7 +11,9 @@ public static void main(String[] args) {
1111

1212
System.out.println(heap.remove());
1313
System.out.println(heap.remove());
14+
System.out.println(heap);
1415
System.out.println(heap.remove());
1516
System.out.println(heap.remove());
17+
System.out.println(heap);
1618
}
1719
}

0 commit comments

Comments
 (0)