Skip to content

Commit d09f50a

Browse files
committed
use sentinel at the bottom of LLRB (perf improv)
1 parent 4038430 commit d09f50a

File tree

2 files changed

+21
-18
lines changed

2 files changed

+21
-18
lines changed

bench.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ var Benchmark = require('benchmark'),
88
// not benchmarking dsjslib & binarySearchTree, they're slow and so not interesting
99

1010
var data = [],
11-
N = 10000;
11+
N = 2000;
1212

1313
for (var i = 0; i < N; i++) {
1414
data[i] = Math.floor(Math.random() * N);

llrb.js

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,23 @@ function llrb(compare) {
66
return new LLRBTree(compare);
77
}
88

9+
10+
function Node(key, value, red, left, right) {
11+
this.key = key;
12+
this.value = value;
13+
this.red = red;
14+
this.left = left;
15+
this.right = right;
16+
}
17+
18+
var bottom = new Node(null, null, false);
19+
bottom.left = bottom;
20+
bottom.right = bottom;
21+
22+
923
function LLRBTree(compare) {
1024
this.compare = compare || defaultCompare;
25+
this.root = bottom;
1126
}
1227

1328
LLRBTree.prototype = {
@@ -16,7 +31,7 @@ LLRBTree.prototype = {
1631
var n = this.root,
1732
cmp = this.compare;
1833

19-
while (n) {
34+
while (n !== bottom) {
2035
var c = cmp(key, n.key);
2136
if (c === 0) return n;
2237
n = c < 0 ? n.left : n.right;
@@ -30,26 +45,18 @@ LLRBTree.prototype = {
3045
}
3146
};
3247

33-
function Node(key, value, red) {
34-
this.key = key;
35-
this.value = value;
36-
this.red = red;
37-
this.left = null;
38-
this.right = null;
39-
}
40-
4148
function insert(h, key, value, compare) {
42-
if (!h) return new Node(key, value, true);
49+
if (h === bottom) return new Node(key, value, true, bottom, bottom);
4350

4451
var c = compare(key, h.key);
4552

4653
if (c < 0) h.left = insert(h.left, key, value, compare);
4754
else if (c > 0) h.right = insert(h.right, key, value, compare);
4855
else h.value = value;
4956

50-
if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
51-
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
52-
if (isRed(h.left) && isRed(h.right)) flipColors(h);
57+
if (h.right.red && !h.left.red) h = rotateLeft(h);
58+
if (h.left.red && h.left.left.red) h = rotateRight(h);
59+
if (h.left.red && h.right.red) flipColors(h);
5360

5461
return h;
5562
}
@@ -58,10 +65,6 @@ function defaultCompare(a, b) {
5865
return a < b ? -1 : a > b ? 1 : 0;
5966
}
6067

61-
function isRed(h) {
62-
return h && h.red;
63-
}
64-
6568
function rotateRight(h) {
6669
var x = h.left;
6770
h.left = x.right;

0 commit comments

Comments
 (0)