Главная » Просмотр файлов » Introduction to Algorithms. (2nd edition) Thomas Cormen_ Charles Leiserson_ Ronad Rivest

Introduction to Algorithms. (2nd edition) Thomas Cormen_ Charles Leiserson_ Ronad Rivest (811417), страница 86

Файл №811417 Introduction to Algorithms. (2nd edition) Thomas Cormen_ Charles Leiserson_ Ronad Rivest (Introduction to Algorithms. (2nd edition) Thomas Cormen_ Charles Leiserson_ Ronad Rivest.pdf) 86 страницаIntroduction to Algorithms. (2nd edition) Thomas Cormen_ Charles Leiserson_ Ronad Rivest (811417) страница 862020-08-25СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 86)

Each internal node x also contains n[x]+ 1 pointers c1[x], c2[x], ..., cn[x]+1[x] to itschildren. Leaf nodes have no children, so their ci fields are undefined.3. The keys keyi[x] separate the ranges of keys stored in each subtree: if ki is any keystored in the subtree with root ci [x], thenk1 ≤ key1[x] ≤ k2 ≤ key2[x] ≤··· ≤ keyn[x][x] ≤ kn[x]+1.4. All leaves have the same depth, which is the tree's height h.5.

There are lower and upper bounds on the number of keys a node can contain. Thesebounds can be expressed in terms of a fixed integer t ≥ 2 called the minimum degreeof the B-tree:a. Every node other than the root must have at least t - 1 keys. Every internalnode other than the root thus has at least t children. If the tree is nonempty, theroot must have at least one key.b. Every node can contain at most 2t - 1 keys.

Therefore, an internal node canhave at most 2t children. We say that a node is full if it contains exactly 2t - 1keys.[1]The simplest B-tree occurs when t = 2. Every internal node then has either 2, 3, or 4 children,and we have a 2-3-4 tree. In practice, however, much larger values of t are typically used.The height of a B-treeThe number of disk accesses required for most operations on a B-tree is proportional to theheight of the B-tree.

We now analyze the worst-case height of a B-tree.Theorem 18.1If n ≥ 1, then for any n-key B-tree T of height h and minimum degree t ≥ 2,Proof If a B-tree has height h, the root contains at least one key and all other nodes contain atleast t - 1 keys. Thus, there are at least 2 nodes at depth 1, at least 2t nodes at depth 2, at least2t2 nodes at depth 3, and so on, until at depth h there are at least 2th-1 nodes.

Figure 18.4illustrates such a tree for h = 3. Thus, the number n of keys satisfies the inequalityFigure 18.4: A B-tree of height 3 containing a minimum possible number of keys. Showninside each node x is n[x].By simple algebra, we get th ≤ (n + 1)/2. Taking base-t logarithms of both sides proves thetheorem.Here we see the power of B-trees, as compared to red-black trees. Although the height of thetree grows as O(lg n) in both cases (recall that t is a constant), for B-trees the base of thelogarithm can be many times larger.

Thus, B-trees save a factor of about lg t over red-blacktrees in the number of nodes examined for most tree operations. Since examining an arbitrarynode in a tree usually requires a disk access, the number of disk accesses is substantiallyreduced.Exercises 18.1-1Why don't we allow a minimum degree of t = 1?Exercises 18.1-2For what values of t is the tree of Figure 18.1 a legal B-tree?Exercises 18.1-3Show all legal B-trees of minimum degree 2 that represent {1, 2, 3, 4, 5}.Exercises 18.1-4As a function of the minimum degree t, what is the maximum number of keys that can bestored in a B-tree of height h?Exercises 18.1-5Describe the data structure that would result if each black node in a red-black tree were toabsorb its red children, incorporating their children with its own.[1]Another common variant on a B-tree, known as a B*-tree, requires each internal node to beat least 2/3 full, rather than at least half full, as a B-tree requires.18.2 Basic operations on B-treesIn this section, we present the details of the operations B-TREE-SEARCH, B-TREECREATE, and B-TREE-INSERT.

In these procedures, we adopt two conventions:••The root of the B-tree is always in main memory, so that a DISK-READ on the root isnever required; a DISK-WRITE of the root is required, however, whenever the rootnode is changed.Any nodes that are passed as parameters must already have had a DISK-READoperation performed on them.The procedures we present are all "one-pass" algorithms that proceed downward from the rootof the tree, without having to back up.Searching a B-treeSearching a B-tree is much like searching a binary search tree, except that instead of making abinary, or "two-way," branching decision at each node, we make a multiway branchingdecision according to the number of the node's children. More precisely, at each internal nodex, we make an (n[x] + 1)-way branching decision.B-TREE-SEARCH is a straightforward generalization of the TREE-SEARCH proceduredefined for binary search trees.

B-TREE-SEARCH takes as input a pointer to the root node xof a subtree and a key k to be searched for in that subtree. The top-level call is thus of theform B-TREE-SEARCH(root[T], k). If k is in the B-tree, B-TREE-SEARCH returns theordered pair (y, i) consisting of a node y and an index i such that keyi[y] = k. Otherwise, thevalue NIL is returned.B-TREE-SEARCH(x, k)1 i ← 12 while i ≤ n[x] and k > keyi[x]3do i ← i + 14 if i ≤ n[x] and k = keyi[x]5then return (x, i)6 if leaf [x]7then return NIL8else DISK-READ(ci[x])9return B-TREE-SEARCH(ci[x], k)Using a linear-search procedure, lines 1-3 find the smallest index i such that k ≤ keyi[x], orelse they set i to n[x] + 1.

Lines 4-5 check to see if we have now discovered the key, returningif we have. Lines 6-9 either terminate the search unsuccessfully (if x is a leaf) or recurse tosearch the appropriate subtree of x, after performing the necessary DISK-READ on that child.Figure 18.1 illustrates the operation of B-TREE-SEARCH; the lightly shaded nodes areexamined during a search for the key R.As in the TREE-SEARCH procedure for binary search trees, the nodes encountered duringthe recursion form a path downward from the root of the tree. The number of disk pagesaccessed by B-TREE-SEARCH is therefore Θ(h) = Θ(logt n), where h is the height of the Btree and n is the number of keys in the B-tree.

Since n[x] < 2t, the time taken by the whileloop of lines 2-3 within each node is O(t), and the total CPU time is O(th) = O(t logt n).Creating an empty B-treeTo build a B-tree T, we first use B-TREE-CREATE to create an empty root node and then callB-TREE-INSERT to add new keys. Both of these procedures use an auxiliary procedureALLOCATE-NODE, which allocates one disk page to be used as a new node in O(1) time.We can assume that a node created by ALLOCATE-NODE requires no DISK-READ, sincethere is as yet no useful information stored on the disk for that node.B-TREE-CREATE(T)1 x ← ALLOCATE-NODE()2 leaf[x] ← TRUE3 n[x] ← 04 DISK-WRITE(x)5 root[T] ← xB-TREE-CREATE requires O(1) disk operations and O(1) CPU time.Inserting a key into a B-treeInserting a key into a B-tree is significantly more complicated than inserting a key into abinary search tree.

As with binary search trees, we search for the leaf position at which toinsert the new key. With a B-tree, however, we cannot simply create a new leaf node andinsert it, as the resulting tree would fail to be a valid B-tree. Instead, we insert the new keyinto an existing leaf node. Since we cannot insert a key into a leaf node that is full, weintroduce an operation that splits a full node y (having 2t - 1 keys) around its median keykeyt[y] into two nodes having t - 1 keys each. The median key moves up into y's parent toidentify the dividing point between the two new trees. But if y's parent is also full, it must besplit before the new key can be inserted, and thus this need to split full nodes can propagateall the way up the tree.As with a binary search tree, we can insert a key into a B-tree in a single pass down the treefrom the root to a leaf.

To do so, we do not wait to find out whether we will actually need tosplit a full node in order to do the insertion. Instead, as we travel down the tree searching forthe position where the new key belongs, we split each full node we come to along the way(including the leaf itself). Thus whenever we want to split a full node y, we are assured that itsparent is not full.Splitting a node in a B-treeThe procedure B-TREE-SPLIT-CHILD takes as input a nonfull internal node x (assumed tobe in main memory), an index i, and a node y (also assumed to be in main memory) such thaty = ci[x] is a full child of x. The procedure then splits this child in two and adjusts x so that ithas an additional child.

Характеристики

Тип файла
PDF-файл
Размер
12,48 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6499
Авторов
на СтудИзбе
303
Средний доход
с одного платного файла
Обучение Подробнее