La descarga está en progreso. Por favor, espere

La descarga está en progreso. Por favor, espere

Unidad 8 Árboles B Bibliografía: “Algoritmos y Estructuras de datos” de Aguilar y Martinez. Unidad 16 Autor: Ing Rolando Simon Titiosky.

Presentaciones similares


Presentación del tema: "Unidad 8 Árboles B Bibliografía: “Algoritmos y Estructuras de datos” de Aguilar y Martinez. Unidad 16 Autor: Ing Rolando Simon Titiosky."— Transcripción de la presentación:

1 Unidad 8 Árboles B Bibliografía: “Algoritmos y Estructuras de datos” de Aguilar y Martinez. Unidad 16 Autor: Ing Rolando Simon Titiosky.

2 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

3 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 63 73 20 30 22 25 29 4 4 13 15 16 33 34 45 62 41 42 47 52 39

4 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. 63 73 20 30 22 25 29 4 4 13 15 16 33 34 45 62 41 42 47 52 39

5 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 abcd >d>d

6 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.

7 Ejemplo de Inserción en Árbol B m=5 Secuencia de Inserción: 6,11,5,4,8,9,12,21 4 4 5 5 6 6 11 4 4 5 5 8 8 6 6 1ro: 6, 11, 5, 4 2do:8 4 4 5 5 6 6 8 8 9 9 11 12 3ro: 9, 12 4 4 5 5 8 8 9 9 12 21 6 6 11 4to: 21

8 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.

9 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

10 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 45 16 26 15 5 5 9 9 79 172 24 18 22 48 57 82 126 29 32 192 232

11 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. 45 16 26 15 5 5 9 9 79 172 24 18 22 48 57 82 126 29 32 192 232

12 Eliminacion de un Árbol B. Ejemplo 45 18 26 15 5 5 9 9 79 172 24 22 48 57 82 126 29 32 192 232 45 16 26 15 5 5 9 9 79 172 24 18 22 48 57 82 126 29 32 192 232 1er Caso: Elimina 16 2do Caso: Elimina 24 45 15 26 5 5 9 9 79 172 22 18 48 57 82 126 29 32 192 232

13 Eliminacion de un Árbol B. Ejemplo 3do Caso: Elimina 22 15 26 5 5 9 9 18 29 32 26 15 5 5 9 9 18 29 32 45 15 26 5 5 9 9 79 172 22 18 48 57 82 126 29 32 192 232 45 26 79 172 45 26 79 172 1ero 2do 3ero4to 45 26 79 172 15 5 5 9 9 18 29 32 48 57 82 126 192 232

14 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.

15 B-tree

16 10 7 16 941419 471914161019 Figura1 – Un ABB o Binary Search Tree con datos almacenados en las hojas

17 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.

18 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:  lg M n 

19 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.

20 471914161019 916 47101419 Figura 2 – Un M-Way tree de orden 3

21 223648 6121826324254 2424 6 8 10 12 14 16 18 19 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 Figura 3 – searching en un M-way tree de orden 4

22 Un ejemplo Consideremos almacenar 10 7 items en un BST y en un M-way tree de orden 10. La altura de los BST será lg(10 7 ) ~ 24. La altura de M-Way tree será log(10 7 ) = 7 (asumiendo que almacenamos justamente 1 record por leaf)

23 B-Tree Definition A B-Tree of order M is an M-Way tree with the following constraints 1.The root is either a leaf or has between 2 and M subtrees 2.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)

24 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

25 223648 6121826324254 2424 6 8 10 12 14 16 18 19 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 Figure 4 – A B-Tree with M = 4 and L = 3

26 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

27 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

28 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.

29 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) <= 4096 12M <= 4104 M <= 342 So choose the largest possible M (making tree as shallow as possible) of 342.

30 Performance of our B-Tree With M = 342 the height of our tree for N students will be  log 342  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  log 342 (25000)  = 2 So 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

31 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)

32 Insert 33 into this B-Tree 223648 6121826324254 2424 6 8 10 12 14 16 18 19 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 Figure 5 – before inserting 33

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 2 nd subtree. Since 32 is greater than 32 we are led to the 3 rd 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)

34 After inserting 33 223648 6121826324254 2424 6 8 10 12 14 16 18 19 20 22 24 26 28 30 32 33 34 36 38 40 42 44 46 48 50 52 54 56 Figure 6 – after inserting 33

35 Now insert 35 This item also belongs in the 3 rd leaf of the 2 nd subtree. However, that leaf is full. Split the leaf in two and update the parent to get the tree in figure 7.

36 After inserting 35 223648 612182632344254 2424 6 8 10 12 14 16 18 19 20 22 24 26 28 30 32 33 36 38 40 42 44 46 48 50 52 54 56 Figure 7 – after inserting 35 34 35

37 Inserting 21 This item belongs in the 4 th leaf of the 1 st 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

38 After inserting 21 22 6 2424 6 8 10 12 14 16 18 19 20 21 26 28 30 32 33 36 38 40 42 44 46 48 50 52 54 56 Figure 8 – after inserting 21 34 35 18 3648 12 20 26 323442 54 22 24

39 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


Descargar ppt "Unidad 8 Árboles B Bibliografía: “Algoritmos y Estructuras de datos” de Aguilar y Martinez. Unidad 16 Autor: Ing Rolando Simon Titiosky."

Presentaciones similares


Anuncios Google