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

Slides:



Advertisements
Presentaciones similares
IBD Clase 7.
Advertisements

Verb Conjugations Easier than you think.
Integrantes: Esteban Jiménez Guesseppe Lozada Mario Rodriguez Gustavo Tenorio Fabio.
Editing Slides With Polaris Office, you can create new .ppt and .pptx presentations or edit your presentation with ease.
WALT: talking about dates and saying when your birthday is WILF: To be able to write & understand months and dates in Spanish to get to a Level 2 To be.
Stem-changing verbs.
REQUISITOS PARA LA GRADUATION DE LAS HIGH SCHOOLS DE ALLIANCE Alliance High School Graduation Requirements.
Estructuras de Datos MC Beatriz Beltrán Martínez.
Heaps Mauro Maldonado Abril/2005. Introducción La estructura heap es frecuentemente usada para implementar colas de prioridad. En este tipo de colas,
Future. Before learning to form the future it in English: I will speak. The future tense in English ALWAYS has the word “will” (or “shall”). It can be.
Spanish –er and –ir verbs. Verbs in General English and Spanish both conjugate verbs. They can be organized as 1rst, 2 nd, and 3 rd person. If you need.
C. E. I. P. MONTEALBO Montalbán de Córdoba (Spain) El presente proyecto ha sido financiado con el apoyo de la Comisión Europea y dentro del Programa de.
La Hora... Telling Time in Spanish. ¿Que hora es? The verb ser is used to express the time of day. Use es when referring to "one o'clock" and use son.
Telling Time.
What time is it? DLT: I can tell time in Spanish..
1 – 999,999,999.
Adjective Agreement Well, the same is true of adjectives. You can’t use the exact same word to describe “mujer” that you use to describe “hombre.” Remember.
The Normal Distribution To calculate the probability of a Normal distribution between a and b:
Objective: I can recognize and accurately use gender agreement. Do Now: Match the following Spanish and English words: 1. Pelirroja a. Good-looking 2.
Verbos con Cambio de Raiz en el Subjuntivo.
Stem-Changing Verbs Lesson Objectives:
-AR Verbs In Spanish, there are three classes (or conjugations) of verbs: those that end in –AR, those that end in –ER, and those that end in –IR. This.
How to Conjugate Regular –AR – Er - IR Verbs in the Present Tense.
7.  El TDA Diccionario.
Write the letter of the correct definition or sentence next to the word below. 1.________ Algebraic Expression 2.________ Equation 3.________ Exponent.
Los verbos reflexivos Objective:
Arboles B (búsqueda externa)
1 B-Trees y AVL Trees. 2 AVL Trees: Topicos Balance en los Trees Chequear el Balance Insertar Single y Doble Rotaciones.
First Grade – High Frequency Word Reading Competition Classroom Competition Created by: Malene Golding School Improvement Officer: Kimberly Fonteno.
Unit 2A: Lesson 2 How to Talk About Your Schedule Gramática- Present tense of –ar verbs.
Definite & indefinite articles
¿Qué haces en la escuela? Question words, objects, yo-go’s.
Indirect Object Pronouns
Las Preguntas (the questions) Tengo una pregunta… Sí, Juan habla mucho con el profesor en clase. No, Juan no habla mucho en clase. s vo s vo Forming.
Time in Spanish Nivel 1. Telling time inSpanish  Time is not TOO different in Spanish.  It is formatted the way time used to be told in English.  It.
Tecnología y Estructura de Costos. Technologies u A technology is a process by which inputs are converted to an output. u E.g. labor, a computer, a projector,
Time Telling time is rather easy. You only need to know the numbers up to 59 to be able to tell the time.
Stem-Changing verbs (verbos con cambios radicales)
Spanish Sentence Structure How can we make better sentences?
Tener -= to have. Tener Tener is our new friend. Tener is our new friend. He is a very strange verb sometimes. He is a very strange verb sometimes. You.
CONJUGATION.
Árboles Equilibrados Estructuras de Datos MC Beatriz Beltrán Martínez Primavera 2015.
Capítulo 3, Paso 1. Cómo decir la hora  ¿Qué hora es?  When you ask the time, you’re using the verb ser, in the 3 rd person SINGULAR. Ser soy I somos.
Associative, Commutative, and Distributive Properties of Addition and Multiplication August 18th Students only need to copy the writing in purple. Students.
JUEVES, EL 10 DE SEPTIEMBRE LT: I WILL RECOGNIZE SOME NEW VOCABULARY WORDS. Go over tests & retake procedures Interpretive Assessment: numbers & alphabet.
Bienvenidos a la clase de español Thank you to those that are coming in and retaking tests and quizzes, turning in late work to improve your grade. Mexico.
unas frases increíblemente útiles some incredibly useful phrases (for dodging conjugation)
I can… Listen and respond to questions in L2 Review concepts from Spanish 1 Recognize when to use SER or ESTAR Use SER/ESTAR in context Recognize when.
Essential ?: How do I use these irregular verbs? How are they different than the verbs I already know?
¿Qué hora es? What time is it? Srta. Kudrak, Español I.
Commands Notes Powerpoint ¡Escucha como usar los mandatos! ©Spanishplans 2012.
Indirect Object Pronouns Original PowerPoint was by Ms. Martin of Tri-Center Community Schools.
Operations Charts Keep these operations charts posted by the wall you usually work out math word problems. Print them in color and paste them on the same.
How would you spell the following word out loud in Spanish? Abuelito.
What time is it? DLT: I can tell time in Spanish..
Antes de empezar – ¿Cómo se llaman estos quehaceres? (Necesito la tarea.)
LOS VERBOS REFLEXIVOS. WRITE: What is a reflexive verb? A reflexive verb describes when a person doing an action is also receiving the action.
English Language II (2). English Language I (2) Warm-up.
Agenda: 26/04/2016 *Boot verbs and jugar *La Familia *Tener: Quack Video *Descripciones Students will be learning new vocabulary with the family and tener.
Bases de datos II Universidad del Cauca Ing. Wilson Ortega.
When attaching object pronouns: 1.Find the natural stress of the original word in question. Voy a llevarselo ahora.
Lunes, 5/10/15  What is the purpose of a subject pronoun?  Give at least one example of a subject pronoun in English.
Present Tense of AR Verbs Las clases de Sra. Schwarz Realidades 1.
To be, or not to be? Let’s start out with one of the most important verbs in Spanish: ser, which means “to be.”
SER and SUBJECT PRONOUNS
First Grade Dual High Frequency Words
Warm-up Fill in the blank with the correct form of the verb “ser” for each subject (p. 35): 1. Yo _______________ de Savannah. 2. Mis amigas ________.
How to Conjugate… SPANISH VERBS.
LOS VERBOS  --ar en el presente.
Astronomy has really big numbers. Distance between Earth and Sun meters kilometers This is the closest star.
Transcripción de la presentación:

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

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

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

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=5 Secuencia de Inserción: 6,11,5,4,8,9,12, ro: 6, 11, 5, 4 2do: ro: 9, to: 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

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

Eliminacion de un Árbol B. Ejemplo er Caso: Elimina 16 2do Caso: Elimina

Eliminacion de un Árbol B. Ejemplo 3do Caso: Elimina ero 2do 3ero4to

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

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:  lg M 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.

Figura 2 – Un M-Way tree de orden 3

Figura 3 – searching en un M-way tree de orden 4

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)

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)

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

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) <= M <= 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  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

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

After inserting Figure 6 – after inserting 33

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.

After inserting Figure 7 – after inserting

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

After inserting Figure 8 – after inserting

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