Assembly Language for Beginners

(Jeff_L) #1

3.18. C++


10

1

0 5

3

2

6

9

100

20

12

11

99

107

101 1001

1010

All keys that are smaller than the node key’s value are stored on the left side.


All keys that are bigger than the node key’s value are stored on the right side.


Hence, the lookup algorithm is straightforward: if the value that you are looking for is smaller than the
current node’s key value: move left, if it is bigger: move right, stop if the value required is equal to the
node key’s value.


Thatiswhythesearchingalgorithmmaysearchfornumbers,textstrings,etc.,aslongasakeycomparison
function is provided.


All keys have unique values.


Having that, one needs≈log 2 nsteps in order to find a key in a balanced binary tree withnkeys. This
implies that≈ 10 steps are needed≈ 1000 keys, or≈ 13 steps for≈ 10000 keys.


Not bad, but the tree has always to be balanced for this: i.e., the keys has to be distributed evenly on all
levels. The insertion and removal operations do some maintenance to keep the tree in a balanced state.


There are several popular balancing algorithms available, including the AVL tree and the red-black tree.


The latter extends each node with a “color” value to simplify the balancing process, hence, each node
may be “red” or “black”.


Both GCC’s and MSVC’sstd::mapandstd::settemplate implementations use red-black trees.


std::sethas only keys.std::mapis the “extended” version of std::set: it also has a value at each node.


MSVC


#include
#include
#include
#include


// Structure is not packed! Each field occupies 4 bytes.
struct tree_node
{
struct tree_node Left;
struct tree_node
Parent;
struct tree_node Right;
char Color; // 0 - Red, 1 - Black
char Isnil;
//std::pair Myval;
unsigned int first; // called Myval in std::set
const char
second; // not present in std::set
};


struct tree_struct
{
struct tree_node *Myhead;
size_t Mysize;
};

Free download pdf