@@ -23,12 +23,100 @@ public boolean isEmpty() {
23
23
24
24
@ Override
25
25
public void insert (E data ) {
26
+ int index = numOfData + 1 ;
26
27
28
+ while (index != 1 ) {
29
+ int parentIndex = getParentIndex (index );
30
+
31
+ // 부모 노드와 비교했을 때, 부모노드보다 우선순위가 높다면 서로의 위치를 바꾼다.
32
+ if (comp .compare (data , (E ) this .heapArr [parentIndex ]) > 0 ) {
33
+ this .heapArr [index ] = this .heapArr [parentIndex ];
34
+ index = parentIndex ;
35
+ } else {
36
+ break ;
37
+ }
38
+ }
39
+
40
+ this .heapArr [index ] = data ;
41
+ this .numOfData += 1 ;
27
42
}
28
43
29
44
@ Override
30
45
public E delete () {
31
- return null ;
46
+ int rootIndex = 1 ;
47
+ E retData = (E ) this .heapArr [rootIndex ]; // 루트노드에 존재하던 데이터
48
+ E lastElement = (E ) this .heapArr [this .numOfData ]; // 마지막 노드
49
+
50
+ int parentIndex = rootIndex ; // 루트로 옮기는 것을 의미
51
+ int childIndex = getHighPriorityChildIndex (parentIndex ); // 더 우선순위인 자식노드
52
+
53
+ while (childIndex > 0 ) { // 부모노드가 단말노드가 아니라면
54
+ if (comp .compare (lastElement , (E ) this .heapArr [childIndex ]) >= 0 ) { // 마지막 노드가 우선순위가 높다면
55
+ break ;
56
+ }
57
+ this .heapArr [parentIndex ] = this .heapArr [childIndex ]; // 자식 노드와 부모노드의 위치를 변경
58
+ parentIndex = childIndex ;
59
+ childIndex = getHighPriorityChildIndex (parentIndex );
60
+ }
61
+
62
+ this .heapArr [parentIndex ] = lastElement ; // 마지막에 위치했던 노드를 한 번에 옮긴다.
63
+ this .numOfData -= 1 ;
64
+ return retData ;
65
+ }
66
+
67
+ /**
68
+ * 부모 노드의 인덱스 반환 요청
69
+ *
70
+ * @param currentIndex 현재 자식 노드의 인덱스
71
+ * @return 부모노드의 인덱스
72
+ */
73
+ private int getParentIndex (int currentIndex ) {
74
+ return currentIndex / 2 ;
32
75
}
33
76
77
+ /**
78
+ * 왼쪽 자식 노드의 인덱스 반환 요청
79
+ *
80
+ * @param parentIndex 부모 노드의 인덱스
81
+ * @return 왼쪽 자식 노드의 인덱스
82
+ */
83
+ private int getLeftChildIndex (int parentIndex ) {
84
+ return parentIndex * 2 ;
85
+ }
86
+
87
+ /**
88
+ * 오른쪽 자식 노드의 인덱스 반환 요청
89
+ *
90
+ * @param parentIndex 부모 노드의 인덱스
91
+ * @return 오른쪽 자식 노드의 인덱스
92
+ */
93
+ private int getRightChildIndex (int parentIndex ) {
94
+ return parentIndex * 2 + 1 ;
95
+ }
96
+
97
+ /**
98
+ * 두 개의 자식 노드 중 우선순위가 더 높은 자식의 인덱스 반환 요청
99
+ *
100
+ * @param currentIndex 판단의 기준이 되는 노드
101
+ * @return 우선순위가 더 높은 자식 노드의 인덱스
102
+ */
103
+ private int getHighPriorityChildIndex (int currentIndex ) {
104
+ int leftChildIndex = this .getLeftChildIndex (currentIndex );
105
+ if (leftChildIndex > this .numOfData ) { // 존재하지 않는 노드라면
106
+ return 0 ;
107
+ }
108
+ if (leftChildIndex == this .numOfData ) { // 왼쪽노드가 마지막 노드라면
109
+ return leftChildIndex ;
110
+ }
111
+
112
+ int rightChildIndex = this .getRightChildIndex (currentIndex );
113
+ E leftChildNode = (E ) this .heapArr [leftChildIndex ];
114
+ E rightChildNode = (E ) this .heapArr [rightChildIndex ];
115
+
116
+ // 우선순위는 낮은것이 더 우위이므로 왼쪽노드가 더 우선순위가 낮다면
117
+ if (comp .compare (leftChildNode , rightChildNode ) < 0 ) {
118
+ return rightChildIndex ;
119
+ }
120
+ return leftChildIndex ;
121
+ }
34
122
}
0 commit comments