File tree Expand file tree Collapse file tree 1 file changed +39
-9
lines changed
src/main/java/ssj/algorithm/collections Expand file tree Collapse file tree 1 file changed +39
-9
lines changed Original file line number Diff line number Diff line change @@ -281,17 +281,47 @@ public BTreeNode<T> deleteChild(int index) {
281
281
return result ;
282
282
}
283
283
284
+ /**
285
+ * 使用修改过的二分查找来提高查找性能。
286
+ * 基本原理就是查找第一个比给定元素大的元素
287
+ *
288
+ * @param value
289
+ * @return
290
+ */
284
291
public BTreeNode <T > searchChild (T value ) {
285
- for (int i = 1 ; i < size (); i += 2 ) {
286
- int cmp_res = getValue (i ).compareTo (value );
287
- //如果非空,那么是最后一个子节点
288
- if (cmp_res < 0 && i == size () - 2 ) {
289
- fullLeaf (i + 1 );
290
- return getChild (i + 1 );
291
- } else if (cmp_res >= 0 ) {
292
- fullLeaf (i - 1 );
293
- return getChild (i - 1 );
292
+ Preconditions .checkNotNull (value );
293
+
294
+ //节点为空,返回第一个子节点
295
+ if (isValueEmpty ()) {
296
+ fullLeaf (0 );
297
+ return getChild (0 );
298
+ } else if (getValue (size () - 2 ).compareTo (value ) < 0 ) {
299
+ //如果非空并且比最后一个节点大
300
+ fullLeaf (size () - 1 );
301
+ return getChild (size () - 1 );
302
+ }
303
+
304
+ for (int start = 1 , end = size () - 2 ; start <= end ; ) {
305
+ int mid = (start + end ) / 2 ;
306
+ if (mid % 2 == 0 ) {
307
+ mid --;
294
308
}
309
+
310
+ int com_res = getValue (mid ).compareTo (value );
311
+
312
+ if (com_res == 0 ) {
313
+ throw new IllegalArgumentException ("dump ele" );
314
+ } else if (com_res > 0 ) {
315
+ if (mid - 2 > 0 && getValue (mid - 2 ).compareTo (value ) >= 0 ) {
316
+ end = mid - 2 ;
317
+ } else {
318
+ fullLeaf (mid - 1 );
319
+ return getChild (mid - 1 );
320
+ }
321
+ } else {
322
+ start = mid + 2 ;
323
+ }
324
+
295
325
}
296
326
return null ;
297
327
}
You can’t perform that action at this time.
0 commit comments