o b0 nodes in level 0In general, N= bd + bd-1 + ... b0.
/ \
o o b1 nodes in level 1
/ \ / \
o o o o b2 nodes in level 2
/ \ / \ / \ / \
o oo oo oo o b3 nodes in level 3
integer key, sorta[] // what we are looking for? & the sorted array (don't have to be ints...)
boolean found // have we found it?
integer botIx, topIx // bottom and top boundaries of the search
integer midIx // middle of current search
integer locIx // for storing the correct location if we find it
botIx = 0, topIx = sorta.length - 1, locIx = -1, found = false; // initialize
while ((found == false) AND (botIx < topIx) do
midIx = (botIx + topIx) / 2; // returns the floor for ints
if (sorta[midIx] == key) {
found = true;
locIx = midIx; // all done!
}
else if (key < sorta[midIx]) {
topIx = midIx - 1;
}
else { // key > sorta[midIx]
botIx = midIx + 1;
}
} // end of while
return locIx; // will have value -1 if key was never found -- calling routine must handle this case!
if (key == self.key) return self;
if (key < self.key)
if (not self.left) return null;
else return self.left.search(key)
if (not self.right) return null;
else return self.right.search(key
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
30, 45, 60 |
31 |
3 |
49 |
20 |
23, 53 |
39 |
10 |
12, 27, 42, 57 |
44 |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
57 |
20 [39] |
39 |
3 [60] |
23 [42] |
42 | 44 |
45 |
27 |
60 |
10 |
30 [49] |
12 [31] |
31 |
49 |
53 |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
57 |
20 |
39 |
3 |
23 |
42 |
44 |
45 |
27 |
60 |
10 |
30 |
12 |
31 |
49 |
53 |