10000 完成B树contains方法并且通过测试。 · ssjssh/javaalgorithm@c203d5e · GitHub
[go: up one dir, main page]

Skip to content

Commit c203d5e

Browse files
author
shengshijun
committed
完成B树contains方法并且通过测试。
修改查找子节点的函数改用二分查找法。
1 parent 1c3b78e commit c203d5e

File tree

1 file changed

+39
-9
lines changed

1 file changed

+39
-9
lines changed

src/main/java/ssj/algorithm/collections/BTree.java

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -281,17 +281,47 @@ public BTreeNode<T> deleteChild(int index) {
281281
return result;
282282
}
283283

284+
/**
285+
* 使用修改过的二分查找来提高查找性能。
286+
* 基本原理就是查找第一个比给定元素大的元素
287+
*
288+
* @param value
289+
* @return
290+
*/
284291
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--;
294308
}
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+
295325
}
296326
return null;
297327
}

0 commit comments

Comments
 (0)
0