unidad 8 Árboles b bibliografía: “algoritmos y estructuras de datos” de aguilar y martinez....
TRANSCRIPT
Unidad 8Árboles B
•Bibliografía: “Algoritmos y Estructuras de datos” de Aguilar y Martinez. Unidad 16
•Autor: Ing Rolando Simon Titiosky.
Problemas de los AVL• Como los datos a buscar están en RAM, los
AVL tienen una Eficiencia F(n)= log n.
• Cuando se tienen un conjunto masivo de datos (ej 1millon de Registros de Clientes de un banco), los datos estarán ubicados en Discos.– El Tiempo de Acceso a disco es notablemente
superior que el de RAM.– Es necesario minimizar estos accesos al disco
y maximizar el uso de RAM
Definición de Árbol B
• Solución: Árboles de Búsqueda m–arios.• Pueden tener hasta m subárboles por padre.• Las claves se organizan en AVL• Objetivo: Que la altura del árbol sea lo suficientemente
pequeña, pues el número de iteraciones y acceso a disco dependerá de ello.
• El Árbol B es una solución particular de esta tecnología
6363 7373
2020 3030
2222 2525 292944 1313 1515 1616 3333 3434
4545 6262
4141 4242 4747 5252
3939
Características del Árbol B• No tienen subárboles vacíos • El Árbol siempre está perfectamente equilibrado.• Pagina: nombre de sus nodos. Se los accede en bloque.
– Todas las Paginas están en el mismo nivel• CantidadDeClavesPorPagina=NumeroDeRamas–1• Todas las Paginas internas, menos la raiz, tienen a lo
sumo m ramas (no vacías) y como mínimo m/2 ramas• La Raiz tiene como máximo m claves, y puede tener
ninguna si el árbol esta vacío.
6363 7373
2020 3030
2222 2525 292944 1313 1515 1616 3333 3434
4545 6262
4141 4242 4747 5252
3939
Definición de Árbol B• Las claves dividen el espacio de claves como en el AVL
– Y estas claves, son las claves de Búsqueda.• Los Árboles que estudiaremos serán de orden m=5
– Un orden mayor aumenta considerablemente la complejidad de la Inserción y Borrado.
– Un Orden menor disminuye la eficiencia de Búsqueda– Numero Máximo de Claves de un Nodo es 4– Numero Máximo de Ramas de un Nodo es 5
• Se rastrea el camino de búsqueda al igual que en el Árbol de Búsqueda.
< a> a< b
> b< c
> c
<d
a b c d
>d
Proceso de Formación de un Árbol B• Un Árbol B crecen “Hacia Arriba”, hacia la raiz
– Las claves que se insertan, siempre van en un nodo hoja.• Por ser perfectamente equilibrado, toda hoja está al mismo nivel.
• Pasos del algoritmo para Insertar una nueva clave:1. Se Busca la clave a insertar en el Árbol. Para lo cual desciende por el
camino de búsqueda hasta una hoja. 2. Si no está en el árbol Entonces Empieza la Inserción. 3. ¿Está Llena la pagina? – Hay Lugar: Entonces Insertar en ese Nodo y finaliza el proceso– Se llenó: No se puede insertar allí:
• Se divide la pagina en dos al mismo nivel que todas las demás. Excepto la clave mediana (es la clave ubicada en la posición 3)
• Con esta clave mediana se sube por el camino de Búsqueda y se comienza el proceso desde el paso 1 nuevamente.
• Esta proceso de ascensión de la clave mediana puede llegar hasta el nodo raiz, que también se partirá y su Mediana, subiendo, será la nueva raiz de todo el árbol B.
Ejemplo de Inserción en Árbol B m=5Secuencia de Inserción: 6,11,5,4,8,9,12,21
44 55 66 1111 44 55 88 1111
66
1ro: 6, 11, 5, 4 2do:8
44 55
66
88 99 1111 1212
3ro: 9, 12
44 55 88 99 1212 2121
66 1111
4to: 21
Búsqueda de una Clave en Árbol B
• Las claves de un nodo B, son claves de búsqueda que dividen el espacio de búsqueda con los Ptrs
• Hay que inspeccionar en cada hoja todas las claves de que consta para definir:– La Posición propia de la clave– El ptr a la rama que nos llevara a la clave
• La función buscar() desciende por el árbol por la ruta determinada por la clave y los nodos.– Una función auxiliar buscarNodo() realiza la inserción
de cada nodo particular.
Codificación de la Inserción en Árbol B
• EL Algoritmo de Inserción se implementa con varias funciones Auxiliares.– Insertar(): es la interfaz de operación.– Empujar():es la función recursiva encargada de
realizar efectivamente la inserción.– buscarNodo(): Determina la rama por donde bajar
para encontrar la clave.– meterHoja(): en caso de insertar una clave sin
division de pagina.– dividirNodo(): Divide el Nodo y determina la clave que
ascendera en el estructura
Eliminación de una clave en Árbol B
• Propiedad de los Árbol B: Si una clave no está en la hoja, su predecesora o sucesora en el Arbol, si lo está (45 no esta, el 32 y el 48 si)– Se procede a sustituirla por la clave sucesora o
predecesora que si está en una hoja.– Pero si la hoja queda con menos del mínimo de
claves, hay que mover claves para restablecer la estructura del Árbol B
4545
1616 2626
151555 99
7979 172172
24241818 2222 4848 5757 8282 1261262929 3232 192192 232232
Algoritmo de Eliminación de una clave en Árbol B• 1er Caso: La Hoja del Sucesor tiene mas del mínimo
– Buscar la Clave y su Sucesor.– Sustituir la clave de búsqueda con la clave sucesora que está en una hoja.
• 2do Caso: La Hoja del Sucesor tiene menos del mínimo, pero los Adyacentes mas.– Examinar los nodos adyacentes al Nodo a Borrar– Si uno de ellos tiene mas claves que la mínima, se puede subir la clave
elegida al nodo Antecedente.– Se baja del Nodo Antecedente la clave hacia el Nodo Problema
• 3er Caso: La Hoja del Sucesor y los Adyacentes tiene menos del mínimo– Tomar el Nodo Problema, el Nodo contiguo y la clave mediana de ambos
(procedente del nodo Antecedente) y se los combina para formar un único Nodo.
– Si deja al Nodo Antecedente menos del mínimo del claves, el proceso se propaga hacia arriba.
– El limite este caso es bajar la Raiz: la altura del Árbol B disminuye.
4545
1616 2626
151555 99
7979 172172
24241818 2222 4848 5757 8282 1261262929 3232 192192 232232
Eliminacion de un Árbol B. Ejemplo
4545
1818 2626
151555 99
7979 172172
24242222 4848 5757 8282 1261262929 3232 192192 232232
4545
1616 2626
151555 99
7979 172172
24241818 2222 4848 5757 8282 1261262929 3232 192192 232232
1er Caso: Elimina 16
2do Caso: Elimina 244545
1515 2626
55 99
7979 172172
22221818 4848 5757 8282 1261262929 3232 192192 232232
Eliminacion de un Árbol B. Ejemplo
3do Caso: Elimina 221515 2626
55 99 1818 2929 3232
2626
151555 99 1818 2929 3232
4545
1515 2626
55 99
7979 172172
22221818 4848 5757 8282 1261262929 3232 192192 232232
4545
2626 7979 172172 45452626 7979 172172
1ero 2do
3ero 4to
45452626 7979 172172
151555 99 1818 2929 3232 4848 5757 8282 126126 192192 232232
Codificación Eliminacion Árbol B
• EL Algoritmo de Eliminación implementa varias funciones Auxiliares.– buscarNodo(): Determina la posición de la
clave en el arbol.– sucesor(): encuentra la clave inmediata si no
es un nodo hoja.– quitar(): si es un nodo hola, quita la clave de
allí.– restablecer():restaura el orden del árbol B.– eliminarRegistro():controla todo el proceso de
borrado.
B-tree
10
7 16
94 14 19
4 71 9 14 1610 19
Figura1 – Un ABB o Binary Search Tree con datos almacenados en las hojas
Observacion
• Almacenar datos solamente en las hojas; todas las hojas están a un mismo nivel.– Nodos interior y exterior tienen diferente
estructura.– Nodo interior almacena una clave y dos
punteros a subarboles.– El camino de búsqueda tiene a lo más largo
de : lg n– Puede almacenar multiples datos en una
hoja.
M-Tree
• Una generalización del modelo BST– Todo nodo interior tiene M punteros a
subtrees y M-1 claves• El BST previo podría haberse llamado “2-tree” o
“M-tree de orden 2”
– si M crece, la altura decrece: lgM n
Un M-tree de orden 3
Figura 2 (siguiente) muestra los mismos datos que Figura 1, almacenando un M-way tree de orden 3. En este ejemplo, M = 3 y h = 2, de manera que el árbol puede soportar 9 leaves.
4 71 9 14 1610 19
9 16
4 7 10 14 19
Figura 2 – Un M-Way tree de orden 3
22 36 48
6 12 18 26 32 42 54
24
68
10
121416
181920
2224
262830
3234
363840
424446
485052
5456
Figura 3 – searching en un M-way tree de orden 4
Un ejemplo
• Consideremos almacenar 107 items en un BST y en un M-way tree de orden 10.
• La altura de los BST será lg(107) ~ 24.• La altura de M-Way tree será log(107 )
= 7 (asumiendo que almacenamos justamente 1 record por leaf)
B-Tree Definition
A B-Tree of order M is an M-Way tree with the following constraints1. The root is either a leaf or
has between 2 and M subtrees2. All interior node (except maybe the root) have
between M / 2 and M subtrees (I.e. each interior node is at least “half full”
3. All leaves are at the same level. A leaf must store between L / 2 and L data elements, where L is a fixed constant >= 1 (I.e. each leaf is at least half full,except when the tree has fewer than L/2 elements)
A B-Tree example
• The following figure (also figure 3) shows a B-Tree with M = 4 and L = 3
• The root node can have between 2 and M=4 subtrees
• Each other interior node can have between M / 2 = 4 / 2 = 2 and M = 4 subtrees and up
to M – 1 = 3 keys.• Each exterior node (leaf) can hold between L / 2 = 3 / 2 = 2 and L = 3 data elements
22 36 48
6 12 18 26 32 42 54
24
68
10
121416
181920
2224
262830
3234
363840
424446
485052
5456
Figure 4 – A B-Tree with M = 4 and L = 3
Designing a B-Tree
• Recall that M-way trees (and therefore B-trees) are often used when there is too much data to fit in memory. Therefore each node and leaf access costs one disk access.
• When designing a B-Tree (choosing the values of M and L), we need to consider the size of the data stored in the leaves, the size of the key and pointers stored in the interior nodes and the size of a disk block
Student Record Example
Suppose our B-Tree stores student records which contain name, address, etc. and other data totaling 1024 bytes.
Further assume that the key to each student record (ssn??) is 8 bytes long.
Assume also that a pointer (really a disk block number, not a memory address) requires 4 bytes
And finally, assume that our disk block is 4096 bytes
Calculating L
L is the number of data records that can be stored in each leaf. Since we want to do just one disk access per leaf, this is the same as the number of data records per disk block.
Since a disk block is 4096 and a data record is 1024, we choose L = 4096 / 1024 = 4 data records per leaf.
Calculating M
Each interior node contains M pointers and M-1 keys. To maximize M (and therefore keep the tree flat and wide) and yet do just one disk access, we have the following relationship
4M + 8 ( M – 1) <= 409612M <= 4104 M <= 342
So choose the largest possible M (making tree as shallow as possible) of 342.
Performance of our B-Tree
With M = 342 the height of our tree for N students will be log342 N/L .
For example, with N = 100,000 (about 10 times the size of UMBC student population) the height of the tree with M = 342 would be no more than 2, because
log342(25000) = 2So any student record can be found in 3 disk
accesses. If the root of the B-Tree is stored in memory, then only 2 disk access is needed
Insertion of X in a B-Tree
• Search to find which leaf X belongs in.• If leaf has room (fewer than L elements), add it
(and write back to disk).• If leaf full, split into two leaves, each with half of
elements. (write new leaves to disk)– Update the keys in the parent– if parent was already full, split in same manner– splits may propagate all the way to the root, in which
case, the root is split (this is how the tree grows in height)
Insert 33 into this B-Tree
22 36 48
6 12 18 26 32 42 54
24
68
10
121416
181920
2224
262830
3234
363840
424446
485052
5456
Figure 5 – before inserting 33
Inserting 33
• Traversing the tree from the root, we find that 33 is less than 36 and is greater than 33, leading us to the 2nd subtree. Since 32 is greater than 32 we are led to the 3rd leaf (the one containing 32 and 34).
• Since there is room for an additional data item in the leaf it is inserted (in sorted order which means reorganizing the leaf)
After inserting 33
22 36 48
6 12 18 26 32 42 54
24
68
10
121416
181920
2224
262830
323334
363840
424446
485052
5456
Figure 6 – after inserting 33
Now insert 35
• This item also belongs in the 3rd leaf of the 2nd subtree. However, that leaf is full.
• Split the leaf in two and update the parent to get the tree in figure 7.
After inserting 35
22 36 48
6 12 18 26 32 34 42 54
24
68
10
121416
181920
2224
262830
3233
363840
424446
485052
5456
Figure 7 – after inserting 35
3435
Inserting 21
• This item belongs in the 4th leaf of the 1st subtree (the leaf containing 18, 19, 20).
• Since the leaf is full, we split it and update the keys in the parent.
• However, the parent is also full, so it must be split and its parent (the root) updated.
• But this would give the root 5 subtrees which is not allowed, so the root must also be split.
• This is the only way the tree grows in height
After inserting 2122
6
24
68
10
121416
1819
2021
262830
3233
363840
424446
485052
5456
Figure 8 – after inserting 21
3435
18 36 48
12 20 26 32 34 42 54
2224
B-tree Deletion• Find leaf containing element to be deleted.• If that leaf is still full enough (still has L / 2
elements after remove) write it back to disk without that element. Then change the key in the ancestor if necessary.
• If leaf is now too empty (has less than L / 2 elements), borrow an element from a neighbor.– If neighbor would be too empty, combine two
leaves into one.– This combining requires updating the parent
which may now have too few subtrees.– If necessary, continue the combining up the tree