text
stringlengths
1
7.76k
source
stringlengths
17
81
17. Sorting and its complexity structures is most of the work done? Insertion sorts remove the first or most easily accessible element from 'unsorted' and search through 'sorted' to find its proper place. Selection sorts search through 'unsorted' to find the next element to be appended to 'sorted'. Insertion sort The i-th step inserts the i-th element into the sorted sequence of the first (i – 1) elements Exhibit 17.1). Exhibit 17.1: Insertion sorts move an easily accessed element to its correct place. Selection sort The i-th step selects the smallest among the n – i + 1 elements not yet sorted, and moves it to the i-th position (Exhibit 17.2). Exhibit 17.2: Selection sorts search for the correct element to move to an easily accessed place. Insertion and selection sorts repeatedly search through a large part of the entire data to find the proper place of insertion or the proper element to be moved. Efficient search requires random access, hence these sorting techniques are used primarily for internal sorting in central memory. Merge sort Merge sorts process (sub)sequences of elements in unidirectional order and thus are well suited for external sorting on secondary storage media that provide sequential access only, such as magnetic tapes; or random access to large blocks of data, such as disks. Merge sorts are also efficient for internal sorting. The basic idea is to merge two sorted sequences of elements, called runs, into one longer sorted sequence. We read each of the input runs, and write the output run, starting with small elements and ending with the large ones. We keep comparing the smallest of the remaining elements on each input run, and append the smaller of the two to the output run, until both input runs are exhausted (Exhibit 17.3). 161
algorithms and data structures_Page_161_Chunk4701
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 17.3: Merge sorts exploit order already present. The processor shown at left in Exhibit 17.4 reads two tapes, A and B. Tape A contains runs 1 and 2; tape B contains runs 3 and 4. The processor merges runs 1 and 3 into the single run 1 & 3 on tape C, and runs 2 and 4 into the single run 2 & 4 on tape D. In a second merge step, the processor shown at the right reads tapes C and D and merges the two runs 1 & 3 and 2 & 4 into one run, 1 & 3 & 2 & 4. Exhibit 17.4: Two merge steps in sequence. Distribution sort Distribution sorts process the representation of an element as a value in a radix number system and use primitive arithmetic operations such as "extract the k-th digit". These sorts do not compare elements directly. They introduce a different model of computation than the sorts based on comparisons, exchanges, insertions, and deletions that we have considered thus far. As an example, consider numbers with at most three digits in radix 4 representation. In a first step these numbers are distributed among four queues according to their least significant digit, and the queues are concatenated in increasing order. The process is repeated for the middle digit, and finally for the leftmost, most significant digit, as shown in Exhibit 17.5 Algorithms and Data Structures 162 A Global Text
algorithms and data structures_Page_162_Chunk4702
17. Sorting and its complexity Exhibit 17.5 Distribution sorts use the radix representation of keys to organize elements in buckets We have now seen the basic ideas on which all sorting algorithms are built. It is more important to understand these ideas than to know dozens of algorithms based on them. To appreciate the intricacy of sorting, you must understand some algorithms in detail: we begin with simple ones that turn out to be inefficient. Simple sorting algorithms that work in time Θ(n2) If you invent your own sorting technique without prior study of the literature, you will probably "discover" a well-known inefficient algorithm that works in time O(n2), requires time Θ(n2) in the worst case, and thus is of time complexity Ω(n2). Your algorithm might be similar to one described below. Consider in-place algorithms that work on an array declared as var A: array[1 .. n] of elt; and place the elements in ascending order. Assume that the comparison operators are defined on values of type elt. Let cbest, caverage, and cworst denote the number of comparisons, and ebest, eaverage, and eworst the number of exchange operations performed in the best, average, and worst case, respectively. Let invaverage denote the average number of inversions in a permutation. Insertion sort (Exhibit 17.6) Let –∞ denote a constant ≤ any key value. The smallest value in the domain often serves as a sentinel –∞. 163
algorithms and data structures_Page_163_Chunk4703
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 17.6: Straight insertion propagates a ripple-effect across the sorted part of the array. A[0] := –∞; for i := 2 to n do begin j := i; while A[j] < A[j – 1] do { A[j] :=: A[j – 1]; { exchange } j := j – 1 } end; This straight insertion sort is an Θ(n) algorithm in the best case and an Θ(n2) algorithm in the average and worst cases. In the program above, the point of insertion is found by a linear search interleaved with exchanges. A binary search is possible but does not improve the time complexity in the average and worst cases, since the actual insertion still requires a linear-time ripple of exchanges. Selection sort (Exhibit 17.7) Exhibit 17.7: Straight selection scans the unsorted part of the array. for i := 1 to n – 1 do begin minindex := i; minkey := A[i]; for j := i + 1 to n do if A[j] < minkey then { minkey := A[j]; minindex := j } A[i] :=: A[minindex] { exchange } end; Algorithms and Data Structures 164 A Global Text
algorithms and data structures_Page_164_Chunk4704
17. Sorting and its complexity The sum in the formula for the number of comparisons reflects the structure of the two nested for loops. The body of the inner loop is executed the same number of times for each of the three cases. Thus this straight selection sort is of time complexity Θ(n2). A lower bound Ω(n · log n) A straightforward counting argument yields a lower bound on the time complexity of any sorting algorithm that collects information about the ordering of the elements by asking only binary questions. A binary question has a two-valued answer: yes or no, true or false. A comparison of two elements, x ≤ y, is the most obvious example, but the following theorem holds for binary questions in general. Theorem: Any sorting algorithm that collects information by asking binary questions only executes at least binary questions both in the worst case, and averaged over all n! permutations. Thus the average and worst-case time complexity of such an algorithm is Ω(n · log n). Proof: A sorting algorithm of the type considered here can be represented by a binary decision tree. Each internal node in such a tree represents a binary question, and each leaf corresponds to a result of the decision process. The decision tree must distinguish each of the n! possible permutations of the input data from all the others; and thus must have at least n! leaves, one for each permutation. Example: The decision tree shown in Exhibit 17.8 collects the information necessary to sort three elements, x, y and z, by comparisons between two elements. Exhibit 17.8 The decision tree shows the possible n! Outcomes when sorting n elements. 165
algorithms and data structures_Page_165_Chunk4705
This book is licensed under a Creative Commons Attribution 3.0 License The average number of binary questions needed by a sorting algorithm is equal to the average depth of the leaves of this decision tree. The lemma following this theorem will show that in a binary tree with k leaves the average depth of the leaves is at least log2k. Therefore, the average depth of the leaves corresponding to the n! permutations is at least log2n!. Since it follows that on average at least n∗log2n1−n ln2 binary questions are needed, that is, the time complexity of each such sorting algorithm is Ω(n · log n) in the average, and therefore also in the worst case. Lemma: In a binary tree with k leaves the average depth of the leaves is at least log2k. Proof: Suppose that the lemma is not true, and let T be the counterexample with the smallest number of nodes. T cannot consist of a single node because the lemma is true for such a tree. If the root r of T has only one child, the subtree T' rooted at this child would contain the k leaves of T that have an even smaller average depth in T' than in T. Since T was the counterexample with the smallest number of nodes, such a T' cannot exist. Therefore, the root r of T must have two children, and there must be kL > 0 leaves in the left subtree and kR > 0 leaves in the right subtree of r (kL + kR = k). Since T was chosen minimal, the kL leaves in the left subtree must have an average depth of at least log2 kL, and the kR leaves in the right subtree must have an average depth of at least log2 kR. Therefore, the average depth of all k leaves in T must be at least It is easy to see that (∗) assumes its minimum value if kL = kR. Since (∗) has the value log2 k if kL = kR = k / 2 we have found a contradiction to our assumption that the lemma is false. Quicksort Quicksort (C. A. R. Hoare, 1962) [Hoa 62] combines the powerful algorithmic principle of divide-and- conquer with an efficient way of moving elements using few exchanges. The divide phase partitions the array into two disjoint parts: the "small" elements on the left and the "large" elements on the right. The conquer phase sorts each part separately. Thanks to the work of the divide phase, the merge phase requires no work at all to combine two partial solutions. Quicksort's efficiency depends crucially on the expectation that the divide phase cuts two sizable subarrays rather than merely slicing off an element at either end of the array (Exhibit 17.9). Algorithms and Data Structures 166 A Global Text
algorithms and data structures_Page_166_Chunk4706
17. Sorting and its complexity Exhibit 17.9: Quicksort partitions the array into the "small" elements on the left and the "large" elements on the right. We chose an arbitrary threshold value m to define "small" as ≤ m, and "large" as ≥ m, thus ensuring that any "small element" ≤ any "large element". We partition an arbitrary subarray A[L .. R] to be sorted by executing a left- to-right scan (incrementing an index i) "concurrently" with a right-to-left scan (decrementing j) (Exhibit 17.10). The left-to-right scan pauses at the first element A[i] ≥ m, and the right-to-left scan pauses at the first element A[j] ≤ m. When both scans have paused, we exchange A[i] and A[j] and resume the scans. The partition is complete when the two scans have crossed over with j < i. Thereafter, quicksort is called recursively for A[L .. j] and A[i .. R], unless one or both of these subarrays consists of a single element and thus is trivially sorted. Example of partitioning (m = 16): 25 23 3 16 4 7 29 6 i j 6 23 3 16 4 7 29 25 i j 6 7 3 16 4 23 29 25 i j 6 7 3 4 16 23 29 25 j i Exhibit 17.10: Scanning the array concurrently from left to right and from right to left. Although the threshold value m appeared arbitrary in the description above, it must meet criteria of correctness and efficiency. Correctness: if either the set of elements ≤ m or the set of elements ≥ m is empty, quicksort fails to terminate. Thus we require that min(xi) ≤ m ≤ max(xi). Efficiency requires that m be close to the median. How do we find the median of n elements? The obvious answer is to sort the elements and pick the middle one, but this leads to a chicken-and-egg problem when trying to sort in the first place. There exist sophisticated algorithms that determine the exact median of n elements in time O(n) in the worst case [BFPRT 72]. The multiplicative constant might be large, but from a theoretical point of view this does not matter. The elements are partitioned into two equal-sized halves, and quicksort runs in time O(n · log n) even in the worst case. From a practical point of view, however, it is not worthwhile to spend much effort in finding the exact median when there are much cheaper ways of finding an acceptable approximation. The following techniques have all been used to pick a threshold m as a "guess at the median": • An array element in a fixed position such as A[(L + R) div 2]. Warning: stay away from either end, A[L] or A[R], as these thresholds lead to poor performance if the elements are partially sorted. • An array element in a random position: a simple technique that yields good results. • The median of three or five array elements in fixed or random positions. 167
algorithms and data structures_Page_167_Chunk4707
This book is licensed under a Creative Commons Attribution 3.0 License • The average between the smallest and largest element. This requires a separate scan of the entire array in the beginning; thereafter, the average for each subarray can be calculated during the previous partitioning process. The recursive procedure 'rqs' is a possible implementation of quicksort. The function 'guessmedian' must yield a threshold that lies on or between the smallest and largest of the elements to be sorted. If an array element is used as the threshold, the procedure 'rqs' should be changed in such a way that after finishing the partitioning process this element is in its final position between the left and right parts of the array. procedure rqs (L, R: 1 .. n); { sorts A[L], … , A[R] } var i, j: 0 .. n + 1; procedure partition; var m: elt; begin { partition } m := guessmedian (L, R); { min(A[L], … , A[R]) ≤ m ≤ max(A[L], … , A[R]) } i := L; j := R; repeat { A[L], … , A[i – 1] ≤ m ≤ A[j + 1], … , A[R] } while A[i] < m do i := i + 1; { A[L], … , A[i – 1] ≤ m ≤ A[i] } while m < A[j] do j := j – 1; { A[j] ≤ m ≤ A[j + 1], … , A[R] } if i ≤ j then begin A[i] :=: A[j]; { exchange } { i ≤ j ⇒ A[i] ≤ m ≤ A[j] } i := i + 1; j := j – 1 { A[L], … , A[i – 1] ≤ m ≤ A[j + 1], … , A[R] } end else { i > j ⇒ i = j + 1 ⇒ exit } end until i > j end; { partition } begin { rqs } partition; if L < j then rqs(L, j); if i < R then rqs(i, R) end; { rqs } An initial call 'rqs(1, n)' with n > 1 guarantees that L < R holds for each recursive call. An iterative implementation of quicksort is given by the following procedure, 'iqs', which sorts the whole array A[1 .. n]. The boundaries of the subarrays to be sorted are maintained on a stack. procedure iqs; const stacklength = … ; type stackelement = record L, R: 1 .. n end; var i, j, L, R, s: 0 .. n; stack: array[1 .. stacklength] of stackelement; procedure partition; { same as in rqs } end; { partition } begin { iqs } s := 1; stack[1].L := 1; stack[1].R := n; repeat L := stack[s].L; R := stack[s].R; s := s – 1; Algorithms and Data Structures 168 A Global Text
algorithms and data structures_Page_168_Chunk4708
17. Sorting and its complexity repeat partition; if j – L < R – i then begin if i < R then { s := s + 1; stack[s].L := i; stack[s].R := R }; R := j end else begin if L < j then { s := s + 1; stack[s].L := L; stack[s].R := j }; L := i end until L ≥ R until s = 0 end; { iqs } After partitioning, 'iqs' pushes the bounds of the larger part onto the stack, thus making sure that part will be sorted later, and sorts the smaller part first. Thus the length of the stack is bounded by log2n. For very small arrays, the overhead of managing a stack makes quicksort less efficient than simpler O(n 2) algorithms, such as an insertion sort. A practically efficient implementation of quicksort might switch to another sorting technique for subarrays of size up to 10 or 20. [Sed 78] is a comprehensive discussion of how to optimize quicksort. Analysis for three cases: best, "typical", and worst Consider a quicksort algorithm that chooses a guessed median that differs from any of the elements to be sorted and thus partitions the array into two parts, one with k elements, the other with n – k elements. The work q(n) required to sort n elements satisfies the recurrence relation The constant b measures the cost of calling quicksort for the array to be sorted. The term a · n covers the cost of partitioning, and the terms q(k) and q(n – k) correspond to the work involved in quicksorting the two subarrays. Most quicksort algorithms partition the array into three parts: the "small" left part, the single array element used to guess the median, and the "large" right part. Their work is expressed by the equation We analyze equation (*); it is close enough to the second equation to have the same asymptotic solution. Quicksort's behavior in the best and worst cases are easy to analyze, but the average over all permutations is not. Therefore, we analyze another average which we call the typical case. Quicksort's best-case behavior is obtained if we guess the correct median that partitions the array into two equal-sized subarrays. For simplicity's sake the following calculation assumes that n is a power of 2, but this assumption does not affect the solution. Then (*) can be rewritten as We use this recurrence equation to calculate 169
algorithms and data structures_Page_169_Chunk4709
This book is licensed under a Creative Commons Attribution 3.0 License and substitute on the right-hand side to obtain Repeated substitution yields The constant q(1), which measures quicksort's work on a trivially sorted array of length 1, and b, the cost of a single procedure call, do not affect the dominant term n · log2n. The constant factor a in the dominant term can be estimated by analyzing the code of the procedure 'partition'. When these details do not matter, we summarize: Quicksort's time complexity in the best case is Θ(n · log n). Quicksort's worst-case behavior occurs when one of the two subarrays consists of a single element after each partitioning. In this case equation (∗) becomes We use this recurrence equation to calculate and substitute on the right-hand side to obtain Repeated substitution yields Therefore the time complexity of quicksort in the worst case is Θ(n2). For the analysis of quicksort's typical behavior we make the plausible assumption that the array is equally likely to get partitioned between any two of its elements: For all k, 1 ≤ k < n, the probability that the array A is partitioned into the subarrays A[1 .. k] and A[k + 1 .. n] is 1 / (n – 1). Then the average work to be performed by quicksort is expressed by the recurrence relation Algorithms and Data Structures 170 A Global Text
algorithms and data structures_Page_170_Chunk4710
17. Sorting and its complexity This recurrence relation approximates the recurrence relation discussed in chapter 16 well enough to have the same solution Since ln 4 ≈ 1.386, quicksort's asymptotic behavior in the typical case is only about 40% worse than in the best case, and remains in Θ(n · log n). [Sed 77] is a thorough analysis of quicksort. Merging and merge sorts The internal sorting algorithms presented so far require direct access to each element. This is reflected in our analyses by treating an array access A[i], or each exchange A[i] :=: A[j], as a primitive operation whose cost is constant (independent of n). This assumption is not valid for elements stored on secondary storage devices such as magnetic tapes or disks. A better assumption that mirrors the realities of external sorting is that the elements to be sorted are stored as a sequential file f. The file is accessed through a file pointer which, at any given time, provides direct access to a single element. Accessing other elements requires repositioning of the file pointer. Sequential files may permit the pointer to advance in one direction only, as in the case of Pascal files, or to move backward and forward. In either case, our theoretical model assumes that the time required for repositioning the pointer is proportional to the distance traveled. This assumption obviously favors algorithms that process (compare, exchange) pairs of adjacent elements, and penalizes algorithms such as quicksort that access elements in random positions. The following external sorting algorithm is based on the merge sort principle. To make optimal use of the available main memory, the algorithm first creates initial runs; a run is a sorted subsequence of elements fi, fi+1, … , fj stored consecutively in file f, fk ≤ fk+1 for all k with i ≤ k ≤ j – 1. Assume that a buffer of capacity m elements is available in main memory to create initial runs of length m (perhaps less for the last run). In processing the r-th run, r = 0, 1, … , we read the m elements fr·m+1, fr·m+2, … , fr·m+m into memory, sort them internally, and write the sorted sequence to a modified file f, which may or may not reside in the same physical storage area as the original file f. This new file f is partially sorted into runs: fk ≤ fk+1 for all k with r · m + 1 ≤ k < r · m + m. At this point we need two files, g and h, in addition to the file f, which contains the initial runs. In a copy phase we distribute the initial runs by copying half of them to g, the other half to h. In the subsequent merge phase each run of g is merged with exactly one run of h, and the resulting new run of double length is written onto f ( Exhibit 17.11). After the first cycle, consisting of a copy phase followed by a merge phase, f contains half as many runs as it did before. After log2(n / m) cycles f contains one single run, which is the sorted sequence of all elements. 171
algorithms and data structures_Page_171_Chunk4711
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 17.11: Each copy-merge cycle halves the number of runs and doubles their lengths. Exercise: a merge sort in main memory Consider the following procedure that sorts the array A: const n = … ; var A: array[1 .. n] of integer; … procedure sort (L, R: 1 .. n); var m: 1 .. n; procedure combine; var B: array [1 .. n] of integer; i, j, k: 1 .. n; begin { combine } i := L; j := m + 1; for k := L to R do if (i > m) cor ((j ≤ R) cand (A[j] < A[i])) then { B[k] := A[j]; j := j + 1 } else { B[k] := A[i]; i := i + 1 } ; for k := L to R do A[k] := B[k] end; { combine } begin { sort} if L < R then { m := (L + R) div 2; sort(L, m); sort(m + 1, R); combine } end; { sort } The relational operators 'cand' and 'cor' are conditional! The procedure is initially called by sort(1,n); (a) Draw a picture to show how 'sort' works on an array of eight elements. (b) Write down a recurrence relation to describe the work done in sorting n elements. (c) Determine the asymptotic time complexity by solving this recurrence relation. (d) Assume that 'sort' is called for m subarrays of equal size, not just for two. How does the asymptotic time complexity change? Solution (a) 'sort' depends on the algorithmic principle of divide and conquer. After dividing an array into a left and a right subarray whose numbers of elements differ by at most one, 'sort' calls itself recursively on these two subarrays. After these two calls are finished, the procedure 'combine' merges the two sorted subarrays A[L .. m] and A[m + 1 .. R] together in B. Finally, B is copied to A. An example is shown in Exhibit 17.12. Algorithms and Data Structures 172 A Global Text
algorithms and data structures_Page_172_Chunk4712
17. Sorting and its complexity Exhibit 17.12: Sorting an array by using a divide-and-conquer scheme. (b) The work w(n) performed while sorting n elements satisfies The first term describes the cost of the two recursive calls of 'sort', the term a · n is the cost of merging the two sorted subarrays, and the constant b is the cost of calling 'sort' for the array. (c) If is substituted in (*∗), we obtain Continuing this substitution process results in 173
algorithms and data structures_Page_173_Chunk4713
This book is licensed under a Creative Commons Attribution 3.0 License since w(1) is constant the time complexity of 'sort' is Θ(n · log n). (d) If 'sort' is called recursively for m subarrays of equal size, the cost w'(n) is solving this recursive equation shows that the time complexity does not change [i.e. it is Θ(n · log n)]. Is it possible to sort in linear time? The lower bound Ω(n · log n) has been derived for sorting algorithms that gather information about the ordering of the elements by binary questions and nothing else. This lower bound need not apply in other situations. Example 1: sorting a permutation of the integers from 1 to n If we know that the elements to be sorted are a permutation of the integers 1 .. n, it is possible to sort in time Θ(n) by storing element i in the array element with index i. Example 2: sorting elements from a finite domain Assume that the elements to be sorted are samples from a finite domain W = 1 .. w. Then it is possible to sort in time Θ(n) if gaps between the elements are allowed (Exhibit 17.13). The gaps can be closed in time Θ(w). Exhibit 17.13: Sorting elements from a finite domain in linear time. Do these examples contradict the lower bound Ω(n · log n)? No, because in these examples the information about the ordering of elements is obtained by asking questions more powerful than binary questions: namely, n- valued questions in Example 1 and w-valued questions in Example 2. A k-valued question is equivalent to log2k binary questions. When this "exchange rate" is taken into consideration, the theoretical time complexities of the two sorting techniques above are Θ(n · log n) and Θ(n · log w), respectively, thus conforming to the lower bound in the section "A lower bound Ω(n · log n)". Sorting algorithms that sort in linear time (expected linear time, but not in the worst case) are described in the literature under the terms bucket sort, distribution sort, and radix sort. Sorting networks The sorting algorithms above are designed to run on a sequential machine in which all operations, such as comparisons and exchanges, are performed one at a time with a single processor. If algorithms are to be efficient, they need to be rethought when the ground rules for their execution change: when the theoretician uses another model of computation, or when they are executed on a computer with a different architecture. This is particularly true of the many different types of multiprocessor architectures that have been built or conceived. When many processors are available to share the workload, questions of how to distribute the work among them, how to synchronize their operation, and how to transport data, prevail. It is not our intention to discuss sorting on general- purpose parallel machines. We wish to illustrate the point that algorithms must be redesigned when the model of Algorithms and Data Structures 174 A Global Text
algorithms and data structures_Page_174_Chunk4714
17. Sorting and its complexity computation changes. For this purpose a discussion of special-purpose sorting networks suffices. The "processors" in a sorting network are merely comparators: Their only function is to compare the values on two input wires and switch them onto two output wires such that the smaller is on top, the larger at the bottom (Exhibit 17.14). Exhibit 17.14: Building block of sorting networks. Comparators are arranged into a network in which n wires enter at the left and n wires exit at the right, as Exhibit 17.15 shows, where each vertical connection joining a pair of wires represents a comparator. The illustration also shows what happens to four input elements, chosen to be 4, 1, 3, 2 in this example, as they travel from left to right through the network. Exhibit 17.15: A comparator network that fails to sort. The output of each comparator performing an exchange is shown in the ovals. A network of comparators is a sorting network if it sorts every input configuration. We consider an input configuration to consist of distinct elements, so that without loss of generality we may regard it as one of the n! permutations of the sequence (1, 2, … , n). A network that sorts a duplicate-free configuration will also sort a configuration containing duplicates. The comparator network above correctly sorts many of its 4! = 24 input configurations, but it fails on the sequence (4, 1, 3, 2). Hence it is not a sorting network. It is evident that a network with a sufficient number of comparators in the right places will sort correctly, but as the example above shows, it is not immediately evident what number suffices or how the comparators should be placed. The network in Exhibit 17.16 shows that five comparators, arranged judiciously, suffice to sort four elements. Exhibit 17.16: Five comparators suffice to sort four elements. How can we tell if a given network sorts successfully? Exhaustive testing is feasible for small networks such as the one above, where we can trace the flow of all 4! = 24 input configurations. Networks with a regular structure 175 c1 c2 c3 c4 c5
algorithms and data structures_Page_175_Chunk4715
This book is licensed under a Creative Commons Attribution 3.0 License usually admit a simpler correctness proof. For this example, we observe that c1, c2, and c3 place the smallest element on the top wire. Similarly, c1, c2, and c4 place the largest on the bottom wire. This leaves the middle two elements on the middle two wires, which c5 then puts into place. What design principles might lead us to create large sorting networks guaranteed to be correct? Sorting algorithms designed for a sequential machine cannot, in general, be mapped directly into network notation, because the network is a more restricted model of computation: Whereas most sequential sorting algorithms make comparisons based on the outcome of previous comparisons, a sorting network makes the same comparisons for all input configurations. The same fundamental algorithm design principles useful when designing sequential algorithms also apply to parallel algorithms. Divide-and-conquer. Place two sorting networks for n wires next to each other, and combine them into a sorting network for 2 · n wires by appending a merge network to merge their outputs. In sequential computation merging is simple because we can choose the most useful comparison depending on the outcome of previous comparisons. The rigid structure of comparator networks makes merging networks harder to design. Incremental algorithm.We place an n-th wire next to a sorting network with n – 1 wires, and either precede or follow the network by a "ladder" of comparators that tie the extra wire into the existing network, as shown in the following figures. This leads to designs that mirror the straight insertion and selection algorithms in the section "Simple sorting algorithms that work in time Θ(n2) Insertion sort. With the top n – 1 elements sorted, the element on the bottom wire trickles into its correct place. Induction yields the expanded diagram on the right in Exhibit 17.17. Exhibit 17.17: Insertion sort leads by induction to the sorting network on the right. Selection sort. The maximum element first trickles down to the bottom, then the remaining elements are sorted. The expanded diagram is on the right in Exhibit 17.18. Exhibit 17.18: Selection sort leads by induction to the sorting network on the right. Comparators can be shifted along their pair of wires so as to reduce the number of stages, provided that the topology of the network remains unchanged. This compression reduces both insertion and selection sort to the triangular network shown in Exhibit 17.19. Thus we see that the distinction between insertion and selection was more a distinction of sequential order of operations rather than one of data flow. Algorithms and Data Structures 176 A Global Text
algorithms and data structures_Page_176_Chunk4716
17. Sorting and its complexity Exhibit 17.19: Shifting comparators reduces the number of stages. Any number of comparators that are aligned vertically require only a single unit of time. The compressed triangular network has O(n2) comparators, but its time complexity is 2 · n – 1 ∈ O(n). There are networks with better asymptotic behavior, but they are rather exotic [Knu 73b]. Exercises and programming projects 1. Implement insertion sort, selection sort, merge sort, and quicksort and animate the sorting process for each of these algorithms: for example, as shown in the snapshots in “Algorithm animation”. Compare the number of comparisons and exchange operations needed by the algorithms for different input configurations. 2. What is the smallest possible depth of a leaf in a decision tree for a sorting algorithm? 3. Show that 2 · n – 1 comparisons are necessary in the worst case to merge two sorted arrays containing n elements each. 4. The most obvious method of systematically interchanging the out-of-order pairs of elements in an array var A: array[1 .. n] of elt; is to scan adjacent pairs of elements from bottom to top (imagine that the array is drawn vertically, with A[1] at the top and A[n] at the bottom) repeatedly, interchanging those found out of order: for i := 1 to n – 1 do for j := n downto i + 1 do if A[j – 1] > A[j] then A[j – 1] :=: A[j]; This technique is known as bubble sort, since smaller elements "bubble up" to the top. (a) Explain by words, figures, and an example how bubble sort works. Show that this algorithm sorts correctly. (b) Determine the exact number of comparisons and exchange operations that are performed by bubble sort in the best, average, and worst case. (c) What is the worst-case time complexity of this algorithm? 5. A sorting algorithm is called stable if it preserves the original order of equal elements. Which of the sorting algorithms discussed in this chapter is stable? 6. Assume that quicksort chooses the threshold m as the first element of the sequence to be sorted. Show that the running time of such a quicksort algorithm is Θ(n2) when the input array is sorted in nonincreasing or nondecreasing order. 7. Find a worst-case input configuration for a quicksort algorithm that chooses the threshold m as the median of the first, middle, and last elements of the sequence to be sorted. 8. Array A contains m and array B contains n different integers which are not necessarily ordered: const m = … ; { length of array A } n = … ; { length of array B } var A: array[1 .. m] of integer; B: array[1 .. n] of integer; 177
algorithms and data structures_Page_177_Chunk4717
This book is licensed under a Creative Commons Attribution 3.0 License A duplicate is an integer that is contained in both A and B. Problem: How many duplicates are there in A and B? (a) Determine the time complexity of the brute-force algorithm that compares each integer contained in one array to all integers in the other array. (b) Write a more efficient function duplicates: integer; Your solution may rearrange the integers in the arrays. (c) What is the worst-case time complexity of your improved algorithm? Algorithms and Data Structures 178 A Global Text
algorithms and data structures_Page_178_Chunk4718
This book is licensed under a Creative Commons Attribution 3.0 License Part V: Data structures The tools of bookkeeping When thinking of algorithms we emphasize a dynamic sequence of actions: "Take this and do that, then that, then … ." In human experience, "take" is usually a straightforward operation, whereas "do" means work. In programming, on the other hand, there are lots of interesting examples where "do" is nothing more complex than incrementing a counter or setting a bit; but "take" triggers a long, sophisticated search. Why do we need fancy data structures at all? Why can't we just spread out the data on a desk top? Everyday experience does not prepare us to appreciate the importance of data structure—it takes programming experience to see that algorithms are nothing without data structures. The algorithms presented so far were carefully chosen to require only the simplest of data structures: static arrays. The geometric algorithms of Part VI, on the other hand, and lots of other useful algorithms, depend on sophisticated data structures for their efficiency. The key insight in understanding data structures is the recognition that an algorithm in execution is, at all times, in some state, chosen from a potentially huge state space. The state records such vital information as what steps have already been taken with what results, and what remains to be done. Data structures are the bookkeepers that record all this state information in a tidy manner so that any part can be accessed and updated efficiently. The remarkable fact is that there are a relatively small number of standard data structures that turn out to be useful in the most varied types of algorithms and problems, and constitute essential knowledge for any programmer. The literature on data structures. Whereas one can present some algorithms without emphasizing data structures, as we did in Part III, it appears pointless to discuss data structures without some of the typical algorithms that use them; at the very least, access and update algorithms form a necessary part of any data structure. Accordingly, a new data structure is typically published in the context of a particular new algorithm. Only later, as one notices its general applicability, it may find its way into textbooks. The data structures that have become standard today can be found in many books, such as [AHU 83], [CLR 90], [GB 91], [HS 82], [Knu 73a], [Knu 73b], [Meh 84a], [Meh 84c], [RND 77], [Sam 90a], [Sam 90b], [Tar 83], and [Wir 86]. Algorithms and Data Structures 179 A Global Text
algorithms and data structures_Page_179_Chunk4719
This book is licensed under a Creative Commons Attribution 3.0 License 18. What is a data structure? Learning objectives: • data structures for manual use (e.g. edge-notched cards) • general-purpose data structures • abstract data types specify functional properties only • data structures include access and maintenance algorithms and their implementation • performance criteria and measures • asymptotics Data structures old and new The discipline of data structures, as a systematic body of knowledge, is truly a creation of computer science. The question of how best to organize data was a lot simpler to answer in the days before the existence of computers: the organization had to be simple, because there was no automatic device that could have processed an elaborate data structure, and there is no human being with enough patience to do it. Consider two examples. 1. Manual files and catalogs, as used in business offices and libraries, exhibit several distinct organizing principles, such as sequential and hierarchical order and cross-references. From today's point of view, however, manual files are not well-defined data structures. For good reasons, people did not rigorously define those aspects that we consider essential when characterizing a data structure: what constraints are imposed on the data, both on the structure and its content; what operations the data structure must support; what constraints these operations must satisfy. As a consequence, searching and updating a manual file is not typically a process that can be automated: It requires common sense, and perhaps even expert training, as is the case for a library catalog. 2. In manual computing (with pencil and paper or a nonprogrammable calculator) the algorithm is the focus of attention, not the data structure. Most frequently, the person computing writes data (input, intermediate results, output) in any convenient place within his field of vision, hoping to find them again when he needs them. Occasionally, to facilitate highly repetitive computations (such as income tax declarations), someone designs a form to prompt the user, one operation at a time, to write each data item into a specific field. Such a form specifies both an algorithm and a data structure with considerable formality. Compared to the general-purpose data structures we study in this chapter, however, such forms are highly special purpose. Edge-notched cards are perhaps the most sophisticated data structures ever designed for manual use. Let us illustrate them with the example of a database of English words organized so as to help in solving crossword puzzles. We write one word per card and index it according to which vowels it contains and which ones it does not contain. Across the top row of the card we punch 10 holes labeled A, E, I, O, U, ~A, ~E, ~I, ~O, ~U. When a word, say ABACA, exhibits a given vowel, such as A, we cut a notch above the hole for A; when it does not, such as E, we cut a notch above the hole for ~E (pronounced "not E"). Exhibit 18.1 shows the encoding of the words BEAUTIFUL, EXETER, OMAHA, OMEGA. For example, we search for words that contain at least one E, but no U, by sticking Algorithms and Data Structures 180 A Global Text
algorithms and data structures_Page_180_Chunk4720
18. What is a data structure? two needles through the pack of cards at the holes E and ~U. EXETER and OMEGA will drop out. In principle it is easy to make this sample database more powerful by including additional attributes, such as "A occurs exactly once", "A occurs exactly twice", "A occurs as the first letter in the word", and so on. In practice, a few dozen attributes and thousands of cards will stretch this mechanical implementation of a multikey data structure to its limits of feasibility. Exhibit 18.1: Encoding of different words in edge-notched cards. In contrast to data structures suitable for manual processing, those developed for automatic data processing can be complex. Complexity is not a goal in itself, of course, but it may be an unavoidable consequence of the search for efficiency. Efficiency, as measured by processing time and memory space required, is the primary concern of the discipline of data structures. Other criteria, such as simplicity of the code, play a role, but the first question to be asked when evaluating a data structure that supports a specified set of operations is typically: How much time and space does it require? In contrast to the typical situation of manual computing (consideration of the algorithm comes first, data gets organized only as needed), programmed computing typically proceeds in the opposite direction: First we define the organization of the data rigorously, and from this the structure of the algorithm follows. Thus algorithm design is often driven by data structure design. The range of data structures studied We present generally useful data structures along with the corresponding query, update, and maintenance algorithms; and we develop concepts and techniques designed to organize a vast body of knowledge into a coherent whole. Let us elaborate on both of these goals. "Generally useful" refers to data structures that occur naturally in many applications. They are relatively simple from the point of view of the operations they support—tables and queues of various types are typical examples. These basic data structures are the building blocks from which an applications programmer may construct more elaborate structures tailored to her particular application. Although our collection of specific data structures is rather small, it covers the great majority of techniques an applications programmer is likely to need. We develop a unified scheme for understanding many data structures as special cases of general concepts. This includes: 181
algorithms and data structures_Page_181_Chunk4721
This book is licensed under a Creative Commons Attribution 3.0 License • The separation of abstract data types, which specify only functional properties, from data structures, which also involve aspects of implementation • The classification of all data structures into three major types: implicit data structures, lists, and address computation • A rough assessment of the performance of data structures based on the asymptotic analysis of time and memory requirements The simplest and most common assumption about the elements to be stored in a data structure is that they belong to a domain on which a total order ≤ is defined. Examples: integers ordered by magnitude, a character set with its alphabetic order, character strings of bounded length ordered lexicographically. We assume that each element in a domain requires as much storage as any other element in that domain; in other words, that a data structure manages memory fragments of fixed size. Data objects of greatly variable size or length, such as fragments of text, are typically not considered to be "elements"; instead, they are broken into constituent pieces of fixed size, each of which becomes an element of the data structure. The elements stored in a data structure are often processed according to the order ≤ defined on their domain. The topic of sorting, which we surveyed in “Sorting and its complexity”, is closely related to the study of data structures: Indeed, several sorting algorithms appear "for free" in “List structures”, because every structure that implements the abstract data type dictionary leads to a sorting algorithm by successive insertion of elements, followed by a traversal. Performance criteria and measures The design of data structures is dominated by considerations of efficiency, specifically with respect to time and memory. But efficiency is a multifaceted quality not easily defined and measured. As a scientific discipline, the study of data structures is not directly concerned with the number of microseconds, machine cycles, or bytes required by a specific program processing a given set of data on a particular system. It is concerned with general statements from which an expert practitioner can predict concrete outcomes for a specific processing task. Thus, measuring run times and memory usage is not the typical way to evaluate data structures. We need concepts and notations for expressing the performance of an algorithm independently of machine speed, memory size, programming language, and operating system, and a host of other details that vary from run to run. The solution to this problem emerged over the past two decades as the discipline of computational complexity was developed. In this theory, algorithms are "executed" on some "mathematical machine", carefully designed to be as simple as possible to reflect the bare essentials of a problem. The machine makes available certain primitive operations, and we measure "time" by counting how many of those are executed. For a given algorithm and all the data sets it accepts as input, we analyze the number of primitive operations executed as a function of the size of the data. We are often interested in the worst case, that is, a data set of given size that causes the algorithm to run as long as possible, and the average case, the run time averaged over all data sets of a given size. Among the many different mathematical machines that have been defined in the theory of computation, data structures are evaluated almost exclusively with respect to a theoretical random access machine (RAM). A RAM is essentially a memory with as many locations as needed, each of which can hold a data element, such as an integer, or a real number; and a processing unit that can read from any one or two locations, operate on their content, and write the result back into a third location, all in one time unit. This model is rather close to actual sequential Algorithms and Data Structures 182 A Global Text
algorithms and data structures_Page_182_Chunk4722
18. What is a data structure? computers, except that it incorporates no bounds on the memory size—either in terms of the number of locations or the size of the content of this location. It implies, for example, that a multiplication of two very large numbers requires no more time than 2 · 3 does. This assumption is unrealistic for certain problems, but is an excellent one for most program runs that fit in central memory and do not require variable-precision arithmetic or variable- length data elements. The point is that the programmer has to understand the model and its assumptions, and bears responsibility for applying it judiciously. In this model, time and memory requirements are expressed as functions of input data size, and thus comparing the performance of two data structures is reduced to comparing functions. Asymptotics has proven to be just the right tool for this comparison: sharp enough to distinguish different growth rates, blunt enough to ignore constant factors that differ from machine to machine. As an example of the concise descriptions made possible by asymptotic operation counts, the following table evaluates several implementations for the abstract data type 'dictionary'. The four operations 'find', 'insert', 'delete', and 'next' (with respect to the order ≤) exhibit different asymptotic time requirements for the different implementations. The student should be able to explain and derive this table after studying this part of the book. Ordered array Linear list Balanced tree Hash table find O(log n) O(n) O(log n) O(1)a next O(1) O(1) O(log n) O(n) insert O(n) O(n) O(log n) O(1)a delete O(n) O(n) O(log n) O(1)b a On the average, but not necessarily in the worst case b Deletions are possible but may degrade performance Exercise 1. Describe the manual data structures that have been developed to organize libraries (e.g. catalogs that allow users to get access to the literature in their field of interest, or circulation records, which keep track of who has borrowed what book). Give examples of queries that can be answered by these data structures. 183
algorithms and data structures_Page_183_Chunk4723
This book is licensed under a Creative Commons Attribution 3.0 License 19. Abstract data types Learning objectives: • data abstraction • abstract data types as a tool to describe the functional behavior of data structures • examples of abstract data types: stack, fifo queue, priority queue, dictionary, string Concepts: What and why? A data structure organizes the data to be processed in such a way that the relations among the data elements are reflected and the operations to be performed on the data are supported. How these goals can be achieved efficiently is the central issue in data structures and a major concern of this book. In this chapter, however, we ask not how but what? In particular, we ask: what is the exact functional behavior a data structure must exhibit to be called a stack, a queue, or a dictionary or table? There are several reasons for seeking a formal functional specification for common data structures. The primary motivation is increased generality through abstraction; specifically, to separate input/output behavior from implementation, so that the implementation can be changed without affecting any program that uses a particular data type. This goal led to the earlier introduction of the concept of type in programming languages: the type real is implemented differently on different machines, but usually a program using reals does not require modification when run on another machine. A secondary motivation is the ability to prove general theorems about all data structures that exhibit certain properties, thus avoiding the need to verify the theorem in each instance. This goal is akin to the one that sparked the development of algebra: from the axioms that define a field, we prove theorems that hold equally true for real or complex numbers as well as quaternions. The primary motivation can be further explained by calling on an analogy between data and programs. All programming languages support the concept of procedural abstraction: operations or algorithms are isolated in procedures, thus making it easy to replace or change them without affecting other parts of the program. Other program parts do not know how a certain operation is realized; they know only how to call the corresponding procedure and what effect the procedure call will have. Modern programming languages increasingly support the analogous concept of data abstraction or data encapsulation: the organization of data is encapsulated (e.g. in a module or a package) so that it is possible to change the data structure without having to change the whole program. The secondary motivation for formal specification of data types remains an unrealized goal: although abstract data types are an active topic for theoretical research, it is difficult today to make the case that any theorem of use to programmers has been proved. An abstract data type consists of a domain from which the data elements are drawn, and a set of operations. The specification of an abstract data type must identify the domain and define each of the operations. Identifying and describing the domain is generally straightforward. The definition of each operation consists of a syntactic and a semantic part. The syntactic part, which corresponds to a procedure heading, specifies the operation's name and Algorithms and Data Structures 184 A Global Text
algorithms and data structures_Page_184_Chunk4724
19. Abstract data types the type of each operand. We present the syntax of operations in mathematical function notation, specifying its domain and range. The semantic part attaches a meaning to each operation: what values it produces or what effect it has on its environment. We specify the semantics of abstract data types algebraically by axioms from which other properties may be deduced. This formal approach has the advantage that the operations are defined rigorously for any domain with the required properties. A formal description, however, does not always appeal to intuition, and often forces us to specify details that we might prefer to ignore. When every detail matters, on the other hand, a formal specification is superior to a precise specification in natural language; the latter tends to become cumbersome and difficult to understand, as it often takes many words to avoid ambiguity. In this chapter we consider the abstract data types: stack, first-in-first-out queue, priority queue, and dictionary. For each of these data types, there is an ideal, unbounded version, and several versions that reflect the realities of finite machines. From a theoretical point of view we only need the ideal data types, but from a practical point of view, that doesn't tell the whole story: in order to capture the different properties a programmer intuitively associates with the vague concept "stack", for example, we are forced into specifying different types of stacks. In addition to the ideal unbounded stack, we specify a fixed-length stack which mirrors the behavior of an array implementation, and a variable-length stack which mirrors the behavior of a list implementation. Similar distinctions apply to the other data types, but we only specify their unbounded versions. Let X denote the domain from which the data elements are drawn. Stacks and fifo queues make no assumptions about X; priority queues and dictionaries require that a total order ≤ be defined on X. Let X∗denote the set of all finite sequences over X. Stack A stack is also called a last-in-first-out queue, or lifo queue. A brief informal description of the abstract data type stack (more specifically, unbounded stack, in contrast to the versions introduced later) might merely state that the following operations are defined on it: - create Create a new, empty stack. - empty Return true if the stack is empty. - push Insert a new element. - top Return the element most recently inserted, if the stack is not empty. - pop Remove the element most recently inserted, if the stack is not empty. Exhibit 19.1 helps to clarify the meaning of these words. Exhibit 19.1: Elements are inserted at and removed from the top of the stack. A definition that uses conventional mathematical notation to capture the intention of the description above might define the operations by explicitly showing their effect on the contents of a stack. Let S = X∗ be the set of 185
algorithms and data structures_Page_185_Chunk4725
This book is licensed under a Creative Commons Attribution 3.0 License possible states of a stack, let s = x1 x2 … xk ∈ S be an arbitrary stack state with k elements, and let λ denote the empty state of the stack, corresponding to the null string ∈ X*. Let 'cat' denote string concatenation. Define the functions create: → S empty: S → {true, false} push: S × X → S top: S – {λ} → X pop: S – {λ} → S as follows: ∀s ∈ S,∀x, y ∈ X: create = λ empty(λ) = true s ≠ λ ⇒ empty(s) = false push(s, y) = s cat y = x1 x2 … xk y s ≠ λ top(s) = xk s ≠ pop(s) = x1 x2 … xk–1 This definition refers explicitly to the contents of the stack. If we prefer to hide the contents and refer only to operations and their results, we are led to another style of formal definition of abstract data types that expresses the semantics of the operations by relating them to each other rather than to the explicitly listed contents of a data structure. This is the commonly used approach to define abstract data types, and we follow it for the rest of this chapter. Let S be a set and s0 ∈ S a distinguished state. s0 denotes the empty stack, and S is the set of stack states that can be obtained from the empty stack by performing finite sequences of 'push' and 'pop' operations. The following functions represent stack operations: create: → S empty: S → {true, false} push: S X → S top: S – {s0} → X pop: S – {s0} → S The semantics of the stack operations is specified by the following axioms: ∀s ∈ S, ∀x ∈ X: (1) create = s0 (2) empty(s0) = true (3) empty(push(s, x)) = false (4) top(push(s, x)) = x (5) pop(push(s, x)) = s These axioms can be described in natural language as follows: (1) 'create' produces a stack in the distinguished state. (2) The distinguished state is empty. (3) A stack is not empty after an element has been inserted. (4) The element most recently inserted is on top of the stack. (5) 'pop' is the inverse of 'push'. Notice that 'create' plays a different role from the other stack operations: it is merely a mechanism for causing a stack to come into existence, and could have been omitted by postulating the existence of a stack in state s0. In any implementation, however, there is always some code that corresponds to 'create'. Technical note: we could identify Algorithms and Data Structures 186 A Global Text
algorithms and data structures_Page_186_Chunk4726
19. Abstract data types 'create' with s0, but we choose to make a distinction between the act of creating a new empty stack and the empty state that results from this creation; the latter may recur during normal operation of the stack. Reduced sequences Any s ∈ S is obtained from the empty stack s0 by performing a finite sequence of 'push' and 'pop' operations. By axiom (5) this sequence can be reduced to a sequence that transforms s 0 into s and consists of 'push' operations only. Example s = pop(push(pop(push(push(s0, x), y)), z)) = pop(push(push(s0, x), z)) = push(s0, x) An implementation of a stack may provide the following procedures: procedure create(var s: stack); function empty(s: stack): boolean; procedure push(var s: stack; x: elt); function top(s: stack): elt; procedure pop(var s: stack); Any program that uses this data type is restricted to calling these five procedures for creating and operating on stacks; it is not allowed to use information about the underlying implementation. The procedures may only be called within the constraints of the specification; for example, 'top' and 'pop' may be called only if the stack is not empty: if not empty(s) then pop(s); The specification above assumes that a stack can grow without a bound; it defines an abstract data type called unbounded stack. However, any implementation imposes some bound on the size (depth) of a stack: the size of the underlying array in an array imple→d reflect such→ limitations. The following fixed-length stack describes an implementation as an array of fixed size m, which limits the maximal stack depth. Fixed-length stack create:→ S empty: S → {true, false} full: S → {true, false} push: {s ∈ S: not full(s)} × X → S top: S – {s0} → X pop: S – {s0} → S To specify the behavior of the function 'full' we need an internal function depth: S → {0, 1, 2, … , m} that measures the stack depth, that is, the number of elements currently in the stack. The function 'depth' interacts with the other functions in the following axioms, which specify the stack semantics: ∀s ∈ S, ∀x ∈ X: create = s0 empty(s) = true not full(s) ⇒ empty(push(s, x)) = false depth(s0) = 0 187
algorithms and data structures_Page_187_Chunk4727
This book is licensed under a Creative Commons Attribution 3.0 License not empty(s) ⇒ depth(pop(s)) = depth(s) – 1 not full(s) ⇒ depth(push(s, x)) = depth(s) + 1 full(s) = (depth(s) = m) not full(s) ⇒ top(push(s, x)) = x pop(push(s, x)) = s Variable-length stack A stack implemented as a list may overflow at unpredictable moments depending on the contents of the entire memory, not just of the stack. We specify this behavior by postulating a function 'space-available'. It has no domain and thus acts as an oracle that chooses its value independently of the state of the stack (if we gave 'space-available' a domain, this would have to be the set of states of the entire memory). create: → S empty: S → {true, false} space-available: → {true, false} push: S × X → S top: S – {s0} → X pop: S – {s0} → S ∀s ∈ S, ∀x ∈ X: create = s0 empty(s0) = true space-available ⇒ empty(push(s, x)) = false top(push(s, x)) = x pop(push(s, x)) = s Implementation We have seen that abstract data types cannot capture our intuitive, vague concept of a stack in one single model. The rigor enforced by the formal definition makes us aware that there are different types of stacks with different behavior (quite apart from the issue of the domain type X, which specifies what type of elements are to be stored). This clarity is an advantage whenever we attempt to process abstract data types automatically; it may be a disadvantage for human communication, because a rigorous definition may force us to (over)specify details. The different types of stacks that we have introduced are directly related to different styles of implementation. The fixed-length stack, for example, describes the following implementation: const m = … ; { maximum length of a stack } type elt = … ; stack =record a: array[1 .. m] of elt; d: 0 .. m; { current depth of stack } end; procedure create(var s: stack); begin s.d := 0 end; function empty(s: stack): boolean; begin return(s.d = 0) end; function full(s: stack): boolean; begin return(s.d = m) end; procedure push(var s: stack; x: elt); { not to be called if the stack is full } begin s.d := s.d + 1; s.a[s.d] := x end; Algorithms and Data Structures 188 A Global Text
algorithms and data structures_Page_188_Chunk4728
19. Abstract data types function top(s: stack): elt; { not to be called if the stack is empty } begin return(s.a[s.d]) end; procedure pop(var s: stack); { not to be called if the stack is empty } begin s.d := s.d – 1 end; Since the function 'depth' is not exported (i.e. not made available to the user of this data type), it need not be provided as a procedure. Instead, we have implemented it as a variable d which also serves as a stack pointer. Our implementation assumes that the user checks that the stack is not full before calling 'push', and that it is not empty before calling 'top' or 'pop'. We could, of course, write the procedures 'push', 'top', and 'pop' so as to "protect themselves" against illegal calls on a full or an empty stack simply by returning an error message to the calling program. This requires adding a further argument to each of these three procedures and leads to yet other types of stacks which are formally different abstract data types from the ones we have discussed. First-in-first-out queue The following operations (Exhibit 19.2) are defined for the abstract data type fifo queue (first-in-first-out queue): empty Return true if the queue is empty. enqueue Insert a new element at the tail end of the queue. front Return the front element of the queue. dequeue Remove the front element. Exhibit 19.2: Elements are inserted at the tail and removed from the head of the fifo queue. Let F be the set of queue states that can be obtained from the empty queue by performing finite sequences of 'enqueue' and 'dequeue' operations. f0 ∈ F denotes the empty queue. The following functions represent fifo queue operations: create: → F empty: F → {true, false} enqueue: F × X → F front: F – {f0} → X dequeue: F – {f0} → F The semantics of the fifo queue operations is specified by the following axioms: ∀f ∈ F,∀x ∈ X: (1) create = f0 (2) empty(f0) = true (3) empty(enqueue(f, x)) = false (4) front(enqueue(f0, x)) = x (5) not empty(f) ⇒ front(enqueue(f, x)) = front(f) (6) dequeue(enqueue(f0, x)) = f0 (7) not empty(f) ⇒ dequeue(enqueue(f, x)) = enqueue(dequeue(f), x) 189
algorithms and data structures_Page_189_Chunk4729
This book is licensed under a Creative Commons Attribution 3.0 License Any f ∈ F is obtained from the empty fifo queue f0 by performing a finite sequence of 'enqueue' and 'dequeue' operations. By axioms (6) and (7) this sequence can be reduced to a sequence consisting of 'enqueue' operations only which also transforms f0 into f. Example f = dequeue(enqueue(dequeue(enqueue(enqueue(f0, x), y)), z)) = dequeue(enqueue(enqueue(dequeue(enqueue(f0, x)), y), z)) = dequeue(enqueue(enqueue(f0, y), z)) = enqueue(dequeue(enqueue(f0, y)), z) = enqueue(f0, z) An implementation of a fifo queue may provide the following procedures: procedure create(var f: fifoqueue); function empty(f: fifoqueue): boolean; procedure enqueue(var f: fifoqueue; x: elt); function front(f: fifoqueue): elt; procedure dequeue(var f: fifoqueue); Priority queue A priority queue orders the elements according to their value rather than their arrival time. Thus we assume that a total order ≤ is defined on the domain X. In the following examples, X is the set of integers; a small integer means high priority. The following operations (Exhibit 19.3) are defined for the abstract data type priority queue: - empty Return true if the queue is empty. - insert Insert a new element into the queue. - min Return the element of highest priority contained in the queue. - delete Remove the element of highest priority from the queue. Exhibit 19.3: An element's priority determines its position in a priority queue. Let P be the set of priority queue states that can be obtained from the empty queue by performing finite sequences of 'insert' and 'delete' operations. The empty priority queue is denoted by p0 ∈ P. The following functions represent priority queue operations: create: → P empty: P → {true, false} insert: P × X → P min: P – {p0} → X delete: P – {p0} → P The semantics of the priority queue operations is specified by the following axioms. For x, y ∈ X, the function MIN(x, y) returns the smaller of the two values. Algorithms and Data Structures 190 A Global Text
algorithms and data structures_Page_190_Chunk4730
19. Abstract data types ∀p ∈ P,∀x ∈ X: (1) create = p0 (2) empty(p0) = true (3) empty(insert(p, x)) = false (4) min(insert(p0, x)) = x (5) not empty(p) ⇒ min(insert(p, x)) = MIN(x, min(p)) (6) delete(insert(p0, x)) = p0 (7) not empty(p)⇒ delete (insert(p,x))={ pifxminp insertdeletep,xelse Any p ∈ P is obtained from the empty queue p0 by a finite sequence of 'insert' and 'delete' operations. By axioms (6) and (7) any such sequence can be reduced to a shorter one that also transforms p 0 into p and consists of 'insert' operations only. Example Assume that x < z, y < z. p = delete(insert(delete(insert(insert(p0, x), z)), y)) = delete(insert(insert(delete(insert(p0, x)), z), y)) = delete(insert(insert(p0, z), y)) = insert(p0, z) An implementation of a priority queue may provide the following procedures: procedure create(var p: priorityqueue); function empty(p: priorityqueue): boolean; procedure insert(var p: priorityqueue; x: elt); function min(p: priorityqueue): elt; procedure delete(var p: priorityqueue); Dictionary Whereas stacks and fifo queues are designed to retrieve and process elements depending on their order of arrival, a dictionary (or table) is designed to process elements exclusively by their value (name). A priority queue is a hybrid: insertion is done according to value, as in a dictionary, and deletion according to position, as in a fifo queue. The simplest type of dictionary supports the following operations: - member Return true if a given element is contained in the dictionary. - insert Insert a new element into the dictionary. - delete Remove a given element from the dictionary. Let D be the set of dictionary states that can be obtained from the empty dictionary by performing finite sequences of 'insert' and 'delete' operations. d0 ∈ D denotes the empty dictionary. Then the operations can be represented by functions as follows: create: → D insert: D × X → D member: D × X → {true, false} delete: D × X → D The semantics of the dictionary operations is specified by the following axioms: 191
algorithms and data structures_Page_191_Chunk4731
This book is licensed under a Creative Commons Attribution 3.0 License ∀d ∈ D,∀x, y ∈ X: (1) create = d0 (2) member(d0, x) = false (3) member(insert(d, x), x) = true (4) x ≠ y ⇒ member(insert(d, y), x) = member(d, x) (5) delete(d0, x) = d0 (6) delete(insert(d, x), x) = delete(d, x) (7) x ≠ y ⇒ delete(insert(d, x), y) = insert(delete(d, y), x) Any d ∈ D is obtained from the empty dictionary d0 by a finite sequence of 'insert' and 'delete' operations. By axioms (6) and (7) any such sequence can be reduced to a shorter one that also transforms d0 into d and consists of 'insert' operations only. Example d = delete(insert(insert(insert(d0, x), y), z), y) = insert(delete(insert(insert(d0, x), y), y), z) = insert(delete(insert(d0, x), y), z) = insert(insert(delete(d0, y), x), z) = insert(insert(d0, x), z) This specification allows duplicates to be inserted. However, axiom (6) guarantees that all duplicates are removed if a delete operation is performed. To prevent duplicates, the following axiom is added to the specification above: (8) member(d, x) ⇒ insert(d, x) = d In this case axiom (6) can be weakened to (6') not member(d, x) ⇒ delete(insert(d, x), x) = d An implementation of a dictionary may provide the following procedures: procedure create(var d: dictionary); function member(d: dictionary; x: elt): boolean; procedure insert(var d: dictionary; x: elt); procedure delete(var d: dictionary; x: elt); In actual programming practice, a dictionary usually supports the additional operations 'find', 'predecessor', and 'successor'. 'find' is similar to 'member' but in addition to a true/false answer, provides a pointer to the element found. Both 'predecessor' and 'successor' take a pointer to an element e as an argument, and return a pointer to the element in the dictionary that immediately precedes or follows e, according to the order ≤. Repeated call of 'successor' thus processes the dictionary in sequential order. Exercise: extending the abstract data type 'dictionary' We have defined a dictionary as supporting the three operations 'member', 'insert' and 'delete'. But a dictionary, or table, usually supports additional operations based on a total ordering ≤ defined on its domain X. Let us add two operations that take an argument x ∈ X and deliver its two neighboring elements in the table: succ(x)Return the successor of x in the table. pred(x)Return the predecessor of x in the table. Algorithms and Data Structures 192 A Global Text
algorithms and data structures_Page_192_Chunk4732
19. Abstract data types The successor of x is defined as the smallest of all the elements in the table which are larger than x, or as +∞ if none exists. The predecessor is defined symmetrically: the largest of all the elements in the table that are smaller than x, or –∞. Present a formal specification to describe the behavior of the table. Solution Let T be the set of states of the table, and t0 a special state that denotes the empty table. The functions and axioms are as follows: member: T × X → {true,false} insert: T × X → T delete: T × X → T succ: T × X → X ∪ {+∞} pred: T × X → X ∪ {–∞} ∀t ∈ T,∀x, y ∈ X: member(t0, x) = false member(insert(t, x), x) = true x ≠ y ⇒ member(insert(t, y), x) = member(t, x) delete(t0, x) = t0 delete(insert(t, x), x) = delete(t, x) x ≠ y ⇒ delete(insert(t, x), y) = insert(delete(t, y), x) –∞ < x < +∞ pred(t, x) < x < succ(t, x) succ(t, x) ≠ +∞ ⇒ member(t, succ(t, x)) = true pred(t, x) ≠ –∞ ⇒ member(t, pred(t, x)) = true x < y, member(t, y), y ≠ succ(t, x) ⇒ succ(t, x) < y x > y, member(t, y), y ≠ pred(t, x) ⇒ y < pred(t, x) Exercise: the abstract data type 'string' We define the following operations for the abstract data type string: - empty Return true if the string is empty. - append Append a new element to the tail of the string. - head Return the head element of the string. - tail Remove the head element of the given string. - length Return the length of the string. - find Return the index of the first occurrence of a value within the string. Let X = {a, b, … , z}, and S be the set of string states that can be obtained from the empty string by performing a finite number of 'append' and 'tail' operations. s0 ∈ S denotes the empty string. The operations can be represented by functions as follows: empty: S → {true, false} append: S × X → S head: S – {s0} → X tail: S – {s0} → S length: S → {0, 1, 2, … } find: S × X → {0, 1, 2, … } Examples: empty('abc') = false; append('abc', 'd') = 'abcd'; head('abcd') = 'a'; 193
algorithms and data structures_Page_193_Chunk4733
This book is licensed under a Creative Commons Attribution 3.0 License tail('abcd') = 'bcd'; length('abcd') = 4; find('abcd', 'b') = 2. (a) Give the axioms that specify the semantics of the abstract data type 'string'. (b) The function hchop: S × X → S returns the substring of a string s beginning with the first occurrence of a given value. Similarly, tchop: S × X → S returns the substring of s beginning with head(s) and ending with the last occurrence of a given value. Specify the behavior of these operations by additional axioms. Examples: hchop('abcdabc','c')='cdabc' tchop('abcdabc', 'b') = 'abcdab' (c) The function cat: S × S → S returns the concatenation of two sequences. Specify the behavior of 'cat' by additional axioms. Example: cat('abcd', 'efg') = 'abcdefg' (d) The function reverse: S → S returns the given sequence in reverse order. Specify the behavior of reverse by additional axioms. Example: reverse('abcd') = 'dcba' Solution (a) Axioms for the six 'string' operations: ∀s ∈ S, ∀ x, y ∈ X: empty(s0) = true empty(append(s, x)) = false head(append(s0, x)) = x not empty(s) ⇒ head(s) = head(append(s, x)) tail(append(s0, x)) = s0 not empty(s) ⇒ tail(append(s, x)) = append(tail(s), x) length(s0) = 0 length(append(s, x)) = length(s) + 1 find(s0, x) = 0 x ≠ y, find(s, x) = 0 ⇒ find(append(s, y), x) = 0 find(s, x) = 0 ⇒ find(append(s, x), x) = length(s) + 1 find(s, x) = d > 0 ⇒ find(append(s, y), x) = d (b) Axioms for 'hchop' and 'tchop': ∀s ∈ S, ∀x, y ∈ X: hchop(s0, x) = s0 not empty(s), head(s) = x ⇒ hchop(s, x) = s not empty(s), head(s) ≠ x ⇒ hchop(s, x) = hchop(tail(s), x) tchop(s0, x) = s0 tchop(append(s, x), x) = append(s, x) x ≠ y ⇒ tchop(append(s, y), x) = tchop(s, x) (c) Axioms for 'cat': ∀s, s' ∈ S: cat(s, s0) = s not empty(s') ⇒ cat(s, s') = cat(append(s, head(s')), tail(s')) (d) Axioms for 'reverse': ∀s ∈ S: Algorithms and Data Structures 194 A Global Text
algorithms and data structures_Page_194_Chunk4734
19. Abstract data types reverse(s0) = s0 s ≠ s0 ⇒ reverse(s) = append(reverse(tail(s)), head(s)) Exercises 1. Implement two stacks iν onε array a[1 .. m] in such a way that neither stack overflows unless the total number of elements in both stacks together is m. The operations 'push', 'top', and 'pop' should run in O(1) time. 2. A double-ended queue (deque) can grow and shrink at both ends, left and right, using the procedures 'enqueue-left', 'dequeue-left', 'enqueue-right', and 'dequeue-right'. Present a formal specification to describe the behavior of the abstract data type deque. 3. Extend the abstract data type priority queue by the operation next(x), which returns the element in the priority queue having the next lower priority than x. 195
algorithms and data structures_Page_195_Chunk4735
This book is licensed under a Creative Commons Attribution 3.0 License 20. Implicit data structures Learning objectives: • implicit data structures describe relationships among data elements implicitly by formulas and declarations • array storage • band matrices • sparse matrices • Buffers eliminate temporary speed differences among interacting producer and consumer processes. • fifo queue implemented as a circular buffer • priority queue implemented as a heap • heapsort What is an implicit data structure? An important aspect of the art of data structure design is the efficient representation of the structural relationships among the data elements to be stored. Data is usually modeled as a graph, with nodes corresponding to data elements and links (directed arcs, or bidirectional edges) corresponding to relationships. Relationships often serve a double purpose. Primarily, they define the semantics of the data and thus allow programs to interpret the data correctly. This aspect of relationships is highlighted in the database field: for example, in the entity- relationship model. Secondarily, relationships provide a means of accessing data, by starting at some element and following an access path that leads to other elements of interest. In studying data structures we are mainly concerned with the use of relationships for access to data. When the structure of the data is irregular, or when the structure is highly dynamic (extensively modified at run time), there is no practical alternative to representing the relationships explicitly. This is the domain of list structures, presented in the chapter on “List structures”. When the structure of the data is static and obeys a regular pattern, on the other hand, there are alternatives that compress the structural information. We can often replace many explicit links by a few formulas that tell us where to find the "neighboring" elements. When this approach works, it saves memory space and often leads to faster programs. We use the term implicit to denote data structures in which the relationships among data elements are given implicitly by formulas and declarations in the program; no additional space is needed for these relationships in the data storage. The best known example is the array. If one looks at the area in which an array is stored, it is impossible to derive, from its contents, any relationships among the elements without the information that the elements belong to an array of a given type. Data structures always go hand in hand with the corresponding procedures for accessing and operating on the data. This is particularly true for implicit data structures: They simply do not exist independent of their accessing procedures. Separated from its code, an implicit data structure represents at best an unordered set of data. With the right code, it exhibits a rich structure, as is beautifully illustrated by the heap at the end of this chapter. Algorithms and Data Structures 196 A Global Text
algorithms and data structures_Page_196_Chunk4736
20. Implicit data structures Array storage A two-dimensional array declared as var A: array[1 .. m, 1 .. n] of elt; is usually written in a rectangular shape: A[1, 1] A[1, 2] … A[1, n] A[2, 1] A[2, 2] … A[2, n] … … … … A[m, 1] A[m, 2] … A[m, n] But it is stored in a linearly addressed memory, typically row by row (as shown below) or column by column (as in Fortran) in consecutive storage cells, starting at base address b. If an element fits into one cell, we have address A[1, 1] b A[1, 2] b + 1 … … A[1, n] b + n – 1 A[2, 1] b + n A[2, 2] b + n + 1 … … A[2, n] b + 2 · n – 1 … … A[m, n] b + m · n – 1 If an element of type 'elt' occupies c storage cells, the address α(i, j) of A[i, j] is This linear formula generalizes to k-dimensional arrays declared as var A: array[1 .. m1, 1 .. m2, … , 1 .. mk] of elt; The address α(i1, i2, … , ik) of element A[i1, i2, … , ik] is 197
algorithms and data structures_Page_197_Chunk4737
This book is licensed under a Creative Commons Attribution 3.0 License The point is that access to an element A[i, j, …] invokes evaluation of a (linear) formula α(i, j, …) that tells us where to find this element. A high-level programming language hides most of the details of address computation, except when we wish to take advantage of any special structure our matrices may have. The following types of sparse matrices occur frequently in numerical linear algebra. Band matrices. An n × n matrix M is called a band matrix of width 2 · b + 1 (b = 0, 1, …) if Mi,j = 0 for all i and j with |i – j| > b. In other words, all nonzero elements are located on the main diagonal and in b adjacent minor diagonals on both sides of the main diagonal. If n is large and b is small, much space is saved by storing M in a two- dimensional array A with n · (2 · b + 1) cells rather than in an array with n2 cells: type bandm = array[1 .. n, –b .. b] of elt; var A: bandm; Each row A[i, ·] stores the nonzero elements of the corresponding row of M, namely the diagonal element M i,i, the b elements to the left of the diagonal Mi,i–b, Mi,i–b+1, … , Mi,i–1 and the b elements to the right of the diagonal Mi,i+1, Mi,i+2, … , Mi,i+b. The first and the last b rows of A contain empty cells corresponding to the triangles that stick out from M in Exhibit 20.1. The elements of M are stored in array A such that A[i, j] contains Mi,i+j (1 ≤ i ≤ n, –b ≤ j ≤ b). A total of b · (b + 1) cells in the upper left and lower right of A remain unused. It is not worth saving an additional b · (b + 1) cells by packing the band matrix M into an array of minimal size, as the mapping becomes irregular and the formula for calculating the indices of Mi,j becomes much more complicated. Exhibit 20.1: Extending the diagonals with dummy elements gives the band matrix the shape of a rectangular array. Algorithms and Data Structures 198 A Global Text
algorithms and data structures_Page_198_Chunk4738
20. Implicit data structures Exercise: band matrices (a) Write a procedure add(p, q: bandm; var r: bandm); which adds two band matrices stored in p and q and stores the result in r. (b) Write a procedure bmv(p: bandm; v: … ; var w: … ); which multiplies a band matrix stored in p with a vector v of length n and stores the result in w. Solution (a) procedure add(p, q: bandm; var r: bandm); var i: 1 .. n; j: –b .. b; begin for i := 1 to n do for j := –b to b do r[i, j] := p[i, j] + q[i, j] end; (b) type vector = array[1 .. n] of real; procedure bmv(p: bandm; v: vector; var w: vector); var i: 1 .. n; j: –b .. b; begin for i := 1 to n do begin w[i] := 0.0; for j := –b to b do if (i + j ≥ 1) and (i + j ≤ n) then w[i] := w[i] + p[i, j] · v[i + j] end end; Sparse matrices. A matrix is called sparse if it consists mostly of zeros. We have seen that sparse matrices of regular shape can be compressed efficiently using address computation. Irregularly shaped sparse matrices, on the other hand, do not yield gracefully to compression into a smaller array in such a way that access can be based on address computation. Instead, the nonzero elements may be stored in an unstructured set of records, where each record contains the pair ((i, j), A[i, j]) consisting of an index tuple (i, j) and the value A[i, j]. Any element that is absent from this set is assumed to be zero. As the position of a data element is stored explicitly as an index pair (i, j), this representation is not an implicit data structure. As a consequence, access to a random element of an irregularly shaped sparse matrix typically requires searching for it, and thus is likely to be slower than the direct access to an element of a matrix of regular shape stored in an implicit data structure. Exercise: triangular matrices Let A and B be lower-triangular n × n-matrices; that is, all elements above the diagonal are zero: Ai,j = Bi,j = 0 for i < j. (a) Prove that the inverse (if it exists) and the matrix product of lower-triangular matrices are again lower-triangular. (b) Devise a scheme for storing two lower-triangular matrices A and B in one array C of minimal size. Write a Pascal declaration for C and draw a picture of its contents. (c) Write two functions function A(i, j: 1 .. n): real; function B(i, j: 1 .. n): real; 199
algorithms and data structures_Page_199_Chunk4739
This book is licensed under a Creative Commons Attribution 3.0 License (d) that access C and return the corresponding matrix elements. (e) Write a procedure that computes A := A · B in place: The entries of A in C are replaced by the entries of the product A · B. You may use a (small) constant number of additional variables, independent of the size of A and B. (f) Same as (d), but using A := A–1 · B. Solution (a) The inverse of an n × n-matrix exists iff the determinant of the matrix is non zero. Let A be a lower- triangular matrix for which the inverse matrix B exists, that is, and Let 1 ≤ j ≤ n. Then and therefore B is a lower-triangular matrix. Let A and B be lower-triangular, C := A · B: If i < j, this sum is empty and therefore Ci,j = 0 (i. e. C is lower-triangular). (b) A and B can be stored in an array C of size n · (n + 1) as follows (Exhibit 20.2): const n = … ; var C: array [0 .. n, 1 .. n] of real; Algorithms and Data Structures 200 A Global Text
algorithms and data structures_Page_200_Chunk4740
20. Implicit data structures Exhibit 20.2: A staircase separates two triangular matrices (c) stored in a rectangular array. (graphic does not match) function A(i, j: 1 .. n): real begin if i < j then return(0.0) else return(C[i, j]) end; function B(i, j: 1 .. n): real; begin if i < j then return(0.0) else return(C[n – i, n + 1 – j]) end; (d) Because the new elements of the result matrix C overwrite the old elements of A, it is important to compute them in the right order. Specifically, within every row i of C, elements Ci,j must be computed from left to right, that is, in increasing order of j. procedure mult; var i, j, k: integer; x: real; begin for i := 1 to n do for j := 1 to i do begin x := 0.0; for k := j to i do x := x + A(i, k) · B(k, j); C[i, j] := x end end; (e) procedure invertA; var i, j, k: integer; x: real; begin for i := 1 to n do begin for j := 1 to i – 1 do begin x := 0.0; for k := j to i – 1 do x := x – C[i, k] · C[k, j]; 201
algorithms and data structures_Page_201_Chunk4741
This book is licensed under a Creative Commons Attribution 3.0 License C[i, j] := x / C[i, i] end; C[i, i] := 1.0 / C[i, i] end end; procedure AinvertedmultB; begin invertA; mult end; Implementation of the fixed-length fifo queue as a circular buffer A fifo queue is needed in situations where two processes interact in the following way. A process called producer generates data for a process called consumer. The processes typically work in bursts: The producer may generate a lot of data while the consumer is busy with something else; thus the data has to be saved temporarily in a buffer, from which the consumer takes it as needed. A keyboard driver and an editor are an example of this producer- consumer interaction. The keyboard driver transfers characters generated by key presses into the buffer, and the editor reads them from the buffer and interprets them (e.g. as control characters or as text to be inserted). It is worth remembering, though, that a buffer helps only if two processes work at about the same speed over the long run. If the producer is always faster, any buffer will overflow; if the consumer is always faster, no buffer is needed. A buffer can equalize only temporary differences in speeds. With some knowledge about the statistical behavior of producer and consumer one can usually compute a buffer size that is sufficient to absorb producer bursts with high probability, and allocate the buffer statically in an array of fixed size. Among statically allocated buffers, a circular buffer is the natural implementation of a fifo queue. A circular buffer is an array B, considered as a ring in which the first cell B[0] is the successor of the last cell B[m – 1], as shown in Exhibit 20.3. The elements are stored in the buffer in consecutive cells between the two pointers 'in' and 'out': 'in' points to the empty cell into which the next element is to be inserted; 'out' points to the cell containing the next element to be removed. A new element is inserted by storing it in B[in] and advancing 'in' to the next cell. The element in B[out] is removed by advancing 'out' to the next cell. Algorithms and Data Structures 202 A Global Text
algorithms and data structures_Page_202_Chunk4742
20. Implicit data structures Exhibit 20.3: Insertions move the pointer 'in', deletions the pointer 'out' counterclockwise around the array. Notice that the pointers 'in' and 'out' meet both when the buffer gets full and when it gets empty. Clearly, we must be able to distinguish a full buffer from an empty one, so as to avoid insertion into the former and removal from the latter. At first sight it appears that the pointers 'in' and 'out' are insufficient to determine whether a circular buffer is full or empty. Thus the following implementation uses an additional variable n, which counts how many elements are in the buffer. const m = … ; { length of buffer } type addr = 0 .. m – 1; { index range } var B: array[addr] of elt; {storage} in, out: addr; { access to buffer } n: 0 .. m; { number of elements currently in buffer } procedure create; begin in := 0; out := 0; n := 0 end; function empty(): boolean; begin return(n = 0) end; function full(): boolean; begin return(n = m) end; procedure enqueue(x: elt); { not to be called if the queue is full } begin B[in] := x; in := (in + 1) mod m; n := n + 1 end; function front(): elt; { not to be called if the queue is empty } begin return(B[out]) end; procedure dequeue; { not to be called if the queue is empty } begin out := (out + 1) mod m; n := n – 1 end; 203
algorithms and data structures_Page_203_Chunk4743
This book is licensed under a Creative Commons Attribution 3.0 License The producer uses only 'enqueue' and 'full', as it deletes no elements from the circular buffer. The consumer uses only 'front', 'dequeue', and 'empty', as it inserts no elements. The state of the circular buffer is described by its contents and the values of 'in', 'out', and n. Since 'in' is changed only within 'enqueue', only the producer needs write-access to 'in'. Since 'out' is changed only by 'dequeue', only the consumer needs write-access to 'out'. The variable n, however, is changed by both processes and thus is a shared variable to which both processes have write-access (Exhibit 20.4 (a)). Exhibit 20.4: (a) Producer and consumer both have write-access to shared variable n. (b) The producer has read/write-access to 'in' and read-only-access to 'out', the consumer has read/write-access to 'out' and read-only-access to 'in'. In a concurrent programming environment where several processes execute independently, access to shared variables must be synchronized. Synchronization is overhead to be avoided if possible. The shared variable n becomes superfluous (Exhibit 20.4 (b)) if we use the time-honored trick of leaving at least one cell free as a sentinel. This ensures that 'empty' and 'full', when expressed in terms of 'in' and 'out', can be distinguished. Specifically, we define 'empty' as in = out, and 'full' as (in + 1) mod m = out. This leads to an elegant and more efficient implementation of the fixed-length fifo queue by a circular buffer: const m = … ; { length of buffer } type addr = 0 .. m – 1; { index range } fifoqueue = record B: array[addr] of elt; { storage } in, out: addr { access to buffer } end; procedure create(var f: fifoqueue); begin f.in := 0; f.out := 0 end; function empty(f: fifoqueue): boolean; begin return(f.in = f.out) end; function full(f: fifoqueue): boolean; begin return((f.in + 1) mod m = f.out) end; procedure enqueue(var f: fifoqueue; x: elt); { not to be called if the queue is full } begin f.B[f.in] := x; f.in := ( f.in + 1) mod m end; Algorithms and Data Structures 204 A Global Text
algorithms and data structures_Page_204_Chunk4744
20. Implicit data structures function front(f: fifoqueue): elt; { not to be called if the queue is empty } begin return(f.B[f.out]) end; procedure dequeue(f: fifoqueue); { not to be called if the queue is empty } begin f.out := (f.out + 1) mod m end; Implementation of the fixed-length priority queue as a heap A fixed-length priority queue can be realized by a circular buffer, with elements stored in the cells between 'in' and 'out', and ordered according to their priority such that 'out' points to the element with highest priority (Exhibit 20.5). In this implementation, the operations 'min' and 'delete' have time complexity O(1), since 'out' points directly to the element with the highest priority. But insertion requires finding the correct cell corresponding to the priority of the element to be inserted, and shifting other elements in the buffer to make space. Binary search could achieve the former task in time O(log n), but the latter requires time O(n). Exhibit 20.5: Implementing a fixed-length priority queue by a circular buffer. Shifting elements to make space for a new element costs O(n) time. Implementing a priority queue as a linear list, with elements ordered according to their priority, does not speed up insertion: Finding the correct position of insertion still requires time O(n) (Exhibit 20.6). Exhibit 20.6: Implementing a fixed-length priority queue by a linear list. Finding the correct position for a new element costs O(n) time. The heap is an elegant and efficient data structure for implementing a priority queue. It allows the operation 'min' to be performed in time O(1) and allows both 'insert' and 'delete' to be performed in worst-case time O(log n). A heap is a binary tree that: • obeys a structural property • obeys an order property • is embedded in an array in a certain way Structure: The binary tree is as balanced as possible; all leaves are at two adjacent levels, and the nodes at the bottom level are located as far to the left as possible (Exhibit 20.7). 205
algorithms and data structures_Page_205_Chunk4745
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 20.7: A heap has the structure of an almost complete binary tree. Order: The element assigned to any node is ≤ the elements assigned to any children this node may have (Exhibit 20.8). Exhibit 20.8: The order property implies that the smallest element is stored at the root. The order property implies that the smallest element (the one with top priority) is stored in the root. The 'min' operation returns its value in time O(1), but the most obvious way to delete this element leaves a hole, which takes time to fill. How can the tree be reorganized so as to retain the structural and the order property? The structural condition requires the removal of the rightmost node on the lowest level. The element stored there–13 in our example–is used (temporarily) to fill the vacuum in the root. The root may now violate the order condition, but the latter can be restored by sifting 13 down the tree according to its weight (Exhibit 20.9). If the order condition is violated at any node, the element in this node is exchanged with the smaller of the elements stored in its children; in our example, 13 is exchanged with 2. This sift-down process continues until the element finds its proper level, at the latest when it lands in a leaf. Algorithms and Data Structures 206 A Global Text 1 2 3 9 19 10 8 4 13 6 5 7
algorithms and data structures_Page_206_Chunk4746
20. Implicit data structures Exhibit 20.9: Rebuilding the order property of the tree in Exhibit 20.8 after 1 has been removed and 13 has been moved to the root. Insertion is handled analogously. The structural condition requires that a new node is created on the bottom level at the leftmost empty slot. The new element - 0 in our example - is temporarily stored in this node (Exhibit 20.10). If the parent node now violates the order condition, we restore it by floating the new element upward according to its weight. If the new element is smaller than the one stored in its parent node, these two elements - in our example 0 and 6 - are exchanged. This sift-up process continues until the element finds its proper level, at the latest when it surfaces at the root. Exhibit 20.10: Rebuilding the order property of the tree in Exhibit 20.8 after 0 has been inserted in a new rightmost node on the lowest level. The number of steps executed during the sift-up process and the sift-down process is at most equal to the height of the tree. The structural condition implies that this height is [log2 n]. Thus both 'insert' and 'delete' in a heap work in time O(log n). 207
algorithms and data structures_Page_207_Chunk4747
This book is licensed under a Creative Commons Attribution 3.0 License A binary tree can be implemented in many different ways, but the special class of trees that meets the structural condition stated above has a particularly efficient array implementation. A heap is a binary tree that satisfies the structural and the order condition and is embedded in a linear array in such a way that the children of a node with index i have indices 2 · i and 2 · i + 1 (Exhibit 20.11). Thus the parent of a node with index j has index j div 2. Any subtree of a heap is also a heap, although it may not be stored contiguously. The order property for the heap implies that the elements stored at indices 2 · i and 2 · i + 1 are ≥ the element stored at index i. This order is called the heap order. Exhibit 20.11: Embedding the tree of Exhibit 20.8 in a linear array. The procedure 'restore' is a useful tool for managing a heap. It creates a heap out of a binary tree embedded in a linear array h that satisfies the structural condition, provided that the two subtrees of the root node are already heaps. Procedure 'restore' is applied to subtrees of the entire heap whose nodes are stored between the indices L and R and whose tree structure is defined by the formulas 2 · i and 2 · i + 1. const m = … ; { length of heap } type addr = 1 .. m; var h: array[addr] of elt; procedure restore(L, R: addr); var i, j: addr; begin i := L; while i ≤ (R div 2) do begin if (2 · i < R) cand (h[2 · i + 1] < h[2 · i]) then j := 2 · i + 1 else j := 2 · i; if h[j] < h[i] then { h[i] :=: h[j]; i := j } else i := R end end; Since 'restore' operates along a single path from the root to a leaf in a tree with at most R – L nodes, it works in time O(log (R – L)). Creating a heap An array h can be turned into a heap as follows: for i := n div 2 down to 1 do restore(i, n); Algorithms and Data Structures 208 A Global Text
algorithms and data structures_Page_208_Chunk4748
20. Implicit data structures This is more efficient than repeated insertion of a single element into an existing heap. Since the for loop is executed n div 2 times, and n – i ≤ n, the time complexity for creating a heap with n elements is O(n · log n). A more careful analysis shows that the time complexity for creating a heap is O(n). Heap implementation of the fixed-length priority queue const m = … ; { maximum length of heap } type addr = 1 .. m; priorityqueue = record h: array[addr] of elt; { heap storage } n: 0 .. m { current number of elements } end; procedure restore(var h: array[addr] of elt; L, R: addr); begin … end; procedure create(var p: priorityqueue); begin p.n := 0 end; function empty(p: priorityqueue): boolean; begin return(p.n = 0) end; function full(p: priorityqueue): boolean; begin return(p.n = m) end; procedure insert(var p: priorityqueue; x: elt); { not to be called if the queue is full } var i: 1 .. m; begin p.n := p.n + 1; p.h[p.n] := x; i := p.n; while (i > 1) cand (p.h[i] < p.h[i div 2]) do { p.h[i] :=: p.h[i div 2]; i := i div 2 } end; function min(p: priorityqueue): elt; { not to be called if the queue is empty } begin return(p.h[1]) end; procedure delete(var p: priorityqueue); { not to be called if the queue is empty } begin p.h[1] := p.h[p.n]; p.n := p.n – 1; restore(p.h, 1, p.n) end; Heapsort The heap is the core of an elegant O(n · log n) sorting algorithm. The following procedure 'heapsort' sorts n elements stored in the array h into decreasing order. procedure heapsort(n: addr); { sort elements stored in h[1 .. n] } var i: addr; begin { heap creation phase: the heap is built up } for i := n div 2 downto 1 do restore(i, n); { shift-up phase: elements are extracted from heap in increasing order } for i := n downto 2 do { h[i] :=: h[1]; restore(1, i – 1) } end; Each of the for loops is executed less than n times, and the time complexity of restore is O(log n). Thus heapsort always works in time O(n · log n). 209
algorithms and data structures_Page_209_Chunk4749
This book is licensed under a Creative Commons Attribution 3.0 License Exercises and programming projects 1. Block-diagonal matrices are composed of smaller matrices that line up along the diagonal and have 0 elements everywhere else, as shown in Exhibit 20.12. Show how to store an arbitrary block-diagonal matrix in a minimal storage area, and write down the corresponding address computation formulas. Exhibit 20.12: Structure of a block-diagonal matrix. 2. Let A be an antisymmetric n × n-matrix (i. e., all elements of the matrix satisfy Aij = –Aji). (a) What values do the diagonal elements Aii of the matrix have? (b) How can A be stored in a linear array c of minimal size? What is the size of c? (c) Write a function A(i, j: 1 .. n): real; which returns the value of the corresponding matrix element. 3. Show that the product of two n × n matrices of width 2 · b + 1 (b = 0, 1, …) is again a band matrix. What is the width of the product matrix? Write a procedure that computes the product of two band matrices both having the same width and stores the result as a band matrix of minimal width. 4. Implement a double-ended queue (deque) by a circular buffer. 5. What are the minimum and maximum numbers of elements in a heap of height h? 6. Determine the time complexities of the following operations performed on a heap storing n elements. (a) Searching any element. (b) Searching the largest element (i.e. the element with lowest priority). 7. Implement heapsort and animate the sorting process, for example as shown in the snapshots in “Algorithm animation”. Compare the number of comparisons and exchange operations needed by heapsort and other sorting algorithms (e.g. quicksort) for different input configurations. 8. What is the running time of heapsort on an array h[1 .. n] that is already sorted in increasing order? What about decreasing order? 9. In a k-ary heap, nodes have k children instead of 2 children. (a) How would you represent a k-ary heap in an array? (b) What is the height of a k-ary heap in terms of the number of elements n and k? (c) Implement a priority queue by a k-ary heap. What are the time complexities of the operations 'insert' and 'delete' in terms of n and k? Algorithms and Data Structures 210 A Global Text
algorithms and data structures_Page_210_Chunk4750
This book is licensed under a Creative Commons Attribution 3.0 License 21. List structures Learning objectives: • static vs dynamic data structures • linear, circular and two-way lists • fifo queue implemented as a linear list • breadth-first and depth-first tree traversal • traversing a binary tree without any auxiliary memory: triple tree traversal algorithm • dictionary implemented as a binary search tree • Balanced trees guarantee that dictionary operations can be performed in logarithmic time • height-balanced trees • multiway trees Lists, memory management, pointer variables The spectrum of data structures ranges from static objects, such as a table of constants, to dynamic structures, such as lists. A list is designed so that not only the data values stored in it, but its size and shape can change at run time, due to insertions, deletions, or rearrangement of data elements. Most of the data structures discussed so far can change their size and shape to a limited extent. A circular buffer, for example, supports insertion at one end and deletion at the other, and can grow to a predeclared maximal size. A heap supports deletion at one end and insertion anywhere into an array. In a list, any local change can be done with an effort that is independent of the size of the list - provided that we know the memory locations of the data elements involved. The key to meeting this requirement is the idea of abandoning memory allocation in large contiguous chunks, and instead allocating it dynamically in the smallest chunk that will hold a given object. Because data elements are stored randomly in memory, not contiguously, an insertion or deletion into a list does not propagate a ripple effect that shifts other elements around. An element inserted is allocated anywhere in memory where there is space and tied to other elements by pointers (i.e. addresses of the memory locations where these elements happen to be stored at the moment). An element deleted does not leave a gap that needs to be filled as it would in an array. Instead, it leaves some free space that can be reclaimed later by a memory management process. The element deleted is likely to break some chains that tie other elements together; if so, the broken chains are relinked according to rules specific to the type of list used. Pointers are the language feature used in modern programming languages to capture the equivalent of a memory address. A pointer value is essentially an address, and a pointer variable ranges over addresses. A pointer, however, may contain more information than merely an address. In Pascal and other strongly typed languages, for example, a pointer also references the type definition of the objects it can point to - a feature that enhances the compiler's ability to check for consistent use of pointer variables. Let us illustrate these concepts with a simple example: a one-way linear list is a sequence of cells each of which (except the last) points to its successor. The first cell is the head of the list, the last cell is the tail. Since the Algorithms and Data Structures 211 A Global Text
algorithms and data structures_Page_211_Chunk4751
21. List structures tail has no successor, its pointer is assigned a predefined value 'nil', which differs from the address of any cell. Access to the list is provided by an external pointer 'head'. If the list is empty, 'head' has the value 'nil'. A cell stores an element xi and a pointer to the successor cell (Exhibit 21.1): type cptr = ^cell; cell = record e: elt; next: cptr end; Exhibit 21.1: A one-way linear list. Local operations, such as insertion or deletion at a position given by a pointer p, are efficient. For example, the following statements insert a new cell containing an element y as successor of a cell being pointed at by p ( Exhibit 21.2): new(q); q^.e := y; q^.next := p^.next; p^.next := q; Exhibit 21.2: Insertion as a local operation. The successor of the cell pointed at by p is deleted by a single assignment statement (Exhibit 21.3): p^.next := p^.next^.next; Exhibit 21.3: Deletion as a local operation. An insertion or deletion at the head or tail of this list is a special case to be handled separately. To support insertion at the tail, an additional pointer variable 'tail' may be set to point to the tail element, if it exists. A one-way linear list sometimes is handier if the tail points back to the head, making it a circular list. In a circular list, the head and tail cells are replaced by a single entry cell, and any cell can be reached from any other without having to start at the external pointer 'entry' (Exhibit 21.4). Exhibit 21.4: A circular list combines head and tail into a single entry point 212
algorithms and data structures_Page_212_Chunk4752
This book is licensed under a Creative Commons Attribution 3.0 License In a two-way (or doubly linked) list each cell contains two pointers, one to its successor, the other to its predecessor. The list can be traversed in both directions. Exhibit 21.5 shows a circular two-way list. Exhibit 21.5: A circular two-way or doubly-linked list Exercise: traversal of a singly linked list in both directions Write a recursive procedure traverse(p: cptr); to traverse a singly linked list from the head to the tail and back again. At each visit of a node, call the procedure visit(p: cptr); Solve the same problem iteratively without using any additional storage beyond a few local pointers. Your traversal procedure may modify the structure of the list temporarily. Solution (a) procedure traverse(p: cptr); begin if p ≠ nil then { visit(p); traverse(p^.next); visit(p) } end; The initial call of this procedure is traverse(head); (b) procedure traverse(p: cptr); var o, q: cptr; i: integer; begin for i := 1 to 2 do { forward and back again } begin o := nil; while p ≠ nil do begin visit(p); q := p^.next; p^.next := o; o := p; p := q { the fork advances } end; p := o end end; Traversal becomes simpler if we let the 'next' pointer of the tail cell point to this cell itself: procedure traverse(p: cptr); var o, q: cptr; begin o := nil; while p ≠ nil do begin visit(p); q := p^.next; p^.next := o; o := p; p := q { the fork advances } end end; Algorithms and Data Structures 213 A Global Text
algorithms and data structures_Page_213_Chunk4753
21. List structures The fifo queue implemented as a one-way list It is natural to implement a fifo queue as a one-way linear list, where each element points to the next one "in line". The operation 'dequeue' occurs at the pointer 'head', and 'enqueue' is made fast by having an external pointer 'tail' point to the last element in the queue. A crafty implementation of this data structure involves an empty cell, called a sentinel, at the tail of the list. Its purpose is to make the list-handling procedures simpler and faster by making the empty queue look more like all other states of the queue. More precisely, when the queue is empty, the external pointers 'head' and 'tail' both point to the sentinel rather than having the value 'nil'. The sentinel allows insertion into the empty queue, and deletion that results in an empty queue, to be handled by the same code that handles the general case of 'enqueue' and 'dequeue'. The reader should verify our claim that a sentinel simplifies the code by programming the plausible, but less efficient, procedures which assume that an empty queue is represented by head = tail = nil. The queue is empty if and only if 'head' and 'tail' both point to the sentinel (i.e. if head = tail). An 'enqueue' operation is performed by inserting the new element into the sentinel cell and then creating a new sentinel. type cptr = ^cell; cell = record e: elt; next: cptr end; fifoqueue = record head, tail: cptr end; procedure create(var f: fifoqueue); begin new(f.head); f.tail := f.head end; function empty(f: fifoqueue): boolean; begin return(f.head = f.tail) end; procedure enqueue(var f: fifoqueue; x: elt); begin f.tail^.e := x; new(f.tail^.next); f.tail := f.tail^.next end; function front(f: fifoqueue): elt; { not to be called if the queue is empty } begin return(f.head^.e) end; procedure dequeue(var f: fifoqueue); { not to be called if the queue is empty } begin f.head := f.head^.next end; Tree traversal When we speak of trees in computer science, we usually mean rooted, ordered trees: they have a distinguished node called the root, and the subtrees of any node are ordered. Rooted, ordered trees are best defined recursively: a tree T is either empty, or it is a tuple (N, T1, … , Tk), where N is the root of the tree, and T1, … , Tk is a sequence of trees. Binary trees are the special case k = 2. Trees are typically used to organize data or activities in a hierarchy: a top-level data set or activity is composed of a next level of data or activities, and so on. When one wishes to gather or survey all of the data or activities, it is necessary to traverse the tree, visiting (i.e. processing) the nodes in some systematic order. The visit at each node might be as simple as printing its contents or as complicated as computing a function that depends on all nodes in the tree. There are two major ways to traverse trees: breadth first and depth first. Breadth-first traversal visits the nodes level by level. This is useful in heuristic search, where a node represents a partial solution to a problem, with deeper levels representing more complete solutions. Before pursuing any one solution to a great depth, it may be advantageous to assess all the partial solutions at the present 214
algorithms and data structures_Page_214_Chunk4754
This book is licensed under a Creative Commons Attribution 3.0 License level, in order to pursue the most promising one. We do not discuss breadth-first traversal further, we merely suggest the following: Exercise: breadth-first traversal Decide on a representation for trees where each node may have a variable number of children. Write a procedure for breadth-first traversal of such a tree. Hint: use a fifo queue to organize the traversal. The node to be visited is removed from the head of the queue, and its children are enqueued, in order, at the tail end. Depth-first traversal always moves to the first unvisited node at the next deeper level, if there is one. It turns out that depth-first better fits the recursive definition of trees than breadth-first does and orders nodes in ways that are more often useful. We discuss depth-first for binary trees and leave the generalization to other trees to the reader. Depth-first can generate three basic orders for traversing a binary tree: preorder, inorder, and postorder, defined recursively as: preorder Visit root, traverse left subtree, traverse right subtree. Inorder Traverse left subtree, visit root, traverse right subtree. postorder Traverse left subtree, traverse right subtree, visit root. For the tree in Exhibit 21.6we obtain the orders shown. Exhibit 21.6: Standard orders defined on a binary tree An arithmetic expression can be represented as a binary tree by assigning the operands to the leaves and the operators to the internal nodes. The basic traversal orders correspond to different notations for representing arithmetic expressions. By traversing the expression tree (Exhibit 21.7) in preorder, inorder, or postorder, we obtain the prefix, infix, or suffix notation, respectively. Exhibit 21.7: Standard traversal orders correspond to different notations for arithmetic expressions A binary tree can be implemented as a list structure in many ways. The most common way uses an external pointer 'root' to access the root of the tree and represents each node by a cell that contains a field for an element to be stored, a pointer to the root of the left subtree, and a pointer to the root of the right subtree (Exhibit 21.8). An empty left or right subtree may be represented by the pointer value 'nil', or by pointing at a sentinel, or, as we shall see, by a pointer that points to the node itself. type nptr = ^node; node = record e: elt; L, R: nptr end; var root: nptr; Algorithms and Data Structures 215 A Global Text
algorithms and data structures_Page_215_Chunk4755
21. List structures Exhibit 21.8: Straightforward implementation of a binary tree The following procedure 'traverse' implements any or all of the three orders preorder, inorder, and postorder, depending on how the procedures 'visit1', 'visit2', and 'visit3' process the data in the node referenced by the pointer p. The root of the subtree to be traversed is passed through the formal parameter p. In the simplest case, a visit does nothing or simply prints the contents of the node. procedure traverse(p: nptr); begin if p ≠ nil then begin visit1(p); { preorder } traverse(p^.L); visit2(p); { inorder } traverse(p^.R); visit3(p) { postorder } end end; Traversing a tree involves both advancing from the root toward the leaves, and backing up from the leaves toward the root. Recursive invocations of the procedure 'traverse' build up a stack whose entries contain references to the nodes for which 'traverse' has been called. These entries provide a means of returning to a node after the traversal of one of its subtrees has been finished. The bookkeeping done by a stack or equivalent auxiliary structure can be avoided if the tree to be traversed may be modified temporarily. The following triple-tree traversal algorithm provides an elegant and efficient way of traversing a binary tree without using any auxiliary memory (i.e. no stack is used and it is not assumed that a node contains a pointer to its parent node). The data structure is modified temporarily to retain the information needed to find the way back up the tree and to restore each subtree to its initial condition after traversal. The triple-tree traversal algorithm assumes that an empty subtree is encoded not by a 'nil' pointer, but rather by an L (left) or R (right) pointer that points to the node itself, as shown in Exhibit 21.9. 216
algorithms and data structures_Page_216_Chunk4756
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 21.9: Coding of a leaf used in procedure TTT procedure TTT; var o, p, q: nptr; begin o := nil; p:= root; while p ≠ nil do begin visit(p); q := p^.L; p^.L := p^.R; { rotate left pointer } p^.R := o; { rotate right pointer } o := p; p := q end end; In this procedure the pointers p ("present") and o ("old") serve as a two-pronged fork. The tree is being traversed by the pointer p and the companion pointer o, which always lags one step behind p. The two pointers form a two-pronged fork that runs around the tree, starting in the initial condition with p pointing to the root of the tree, and o = nil. An auxiliary pointer q is needed temporarily to advance the fork. The while loop in 'TTT' is executed as long as p points to a node in the tree and is terminated when p assumes the value 'nil'. The initial value of the o pointer gets saved as a temporary value. First it is assigned to the R pointer of the root, later to the L pointer. Finally, it gets assigned to p, the fork exits from the root of the tree, and the traversal of the tree is complete. The correctness of this algorithm is proved by induction on the number of nodes in the tree. Induction hypothesis H: if at the beginning of an iteration of the while loop, the fork pointer p points to the root of a subtree with n > 0 nodes, and o has a value x that is different from any pointer value inside this subtree, then after 3 · n iterations the subtree will have been traversed in triple order (visiting each node exactly three times), all tree pointers in the subtree will have been restored to their original value, and the fork pointers will have been reversed (i.e. p has the value x and o points to the root of the subtree). Base of induction: H is true for n = 1. Proof: The smallest tree we consider has exactly one node, the root alone. Before the while loop is executed for this subtree, the fork and the tree are in the initial state shown inExhibit 21.10. Exhibit 21.11 shows the state of the fork and the tree after each iteration of the while loop. The node is visited in each iteration. Exhibit 21.10 : Initial configuration for traversing a tree consisting of a single node Algorithms and Data Structures 217 A Global Text
algorithms and data structures_Page_217_Chunk4757
21. List structures Exhibit 21.11: Tracing procedure TTT while traversing the smallest tree Induction step: If H is true for all n, 0 < n ≤ k, H is also true for k + 1. Proof: Consider a tree T with k + 1 nodes. T consists of a root and k nodes shared among the left and right subtrees of the root. Each of these subtrees has ≤ k nodes, so we apply the induction hypothesis to each of them. The following is a highly compressed account of the proof of the induction step, illustrated by Exhibit 21.12. Consider the tree with k + 1 nodes shown in state 1. The root is a node with three fields; the left and right subtrees are shown as triangles. The figure shows the typical case when both subtrees are nonempty. If one of the two subtrees is empty, the corresponding pointer points back to the root; these two cases can be handled similarly to the case n = 1. The fork starts out with p pointing at the root and o pointing at anything outside the subtree being traversed. We want to show that the initial state 1 is transformed in 3 · (k + 1) iterations into the final state 6. In the final state the subtrees are shaded to indicate that they have been correctly traversed; the fork has exited from the root, with p and o having exchanged values. To show that the algorithm correctly transforms state 1 into state 6, we consider the intermediate states 2 to 5, and what happens in each transition. 1 → 2 One iteration through the while loop advances the fork into the left subtree and rotates the pointers of the root. 2 → 3 H applied to the left subtree of the root says that this subtree will be correctly traversed, and the fork will exit from the subtree with pointers reversed. 3 → 4 This is the second iteration through the while loop that visits the root. The fork advances into the right subtree, and the pointers of the root rotate a second time. 4 → 5 H applied to the right subtree of the root says that this subtree will be correctly traversed, and the fork will exit from the subtree with pointers reversed. 5→ 6 This is the third iteration through the while loop that visits the root. The fork moves out of the tree being traversed; the pointers of the root rotate a third time and thereby assume their original values. 218
algorithms and data structures_Page_218_Chunk4758
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 21.12: Trace of procedure TTT, invoking the induction hypothesis Exercise: binary trees Consider a binary tree declared as follows: type nptr = ^node; node = record L, R: nptr end; var root: nptr; (a) If a node has no left or right subtree, the corresponding pointer has the value 'nil'. Prove that a binary tree with n nodes, n > 0, has n + 1 'nil' pointers. Algorithms and Data Structures 219 A Global Text
algorithms and data structures_Page_219_Chunk4759
21. List structures (b) Write a function nodes(…): integer; that returns the number of nodes, and a function depth(…): integer; that returns the depth of a binary tree. The depth of the root is defined to be 0; the depth of any other node is the depth of its parent increased by 1. The depth of the tree is the maximum depth of its nodes. Solution (a) Each node contains two pointers, for a total of 2 · n pointers in the tree. There is exactly one pointer that points to each of n – 1 nodes, none points to the root. Thus 2 · n – (n – 1) = n + 1 pointers are 'nil'. This can also be proved by induction on the number of nodes in the tree. (b) function nodes(p: nptr): integer; begin if p = nil then return(0) else return(nodes(p^.L) + nodes(p^.R) + 1) end; function depth(p: nptr): integer; begin if p = nil then return (–1) else return(1 + max(depth(p^.L), depth(p^.R))) end; where 'max' is function max(a, b: integer): integer; begin if a > b then return(a) else return(b) end; Exercise: list copying Effective memory management sometimes makes it desirable or necessary to copy a list. For example, performance may improve drastically if a list spread over several pages can be compressed into a single page. List copying involves a traversal of the original concurrently with a traversal of the copy, as the latter is being built up. (a) Consider binary trees built from nodes of type 'node' and pointers of type 'nptr'. A tree is accessed through a pointer to the root, which is 'nil' for an empty tree type nptr = ^ node; node = record e: elt; L, R: nptr end; Write a recursive function cptree(p: nptr): nptr; to copy a tree given by a pointer p to its root, and return a pointer to the root of the copy. (b) Consider arbitrary graphs built from nodes of a type similar to the nodes in (a), but they have an additional pointer field cn, intended to point to the copy of a node: type node = record e: elt; L, R: nptr; cn: nptr end; A graph is accessed through a pointer to a node called the origin, and we are only concerned with nodes that can be reached from the origin; this access pointer is 'nil' for an empty graph. Write a recursive function cpgraph(p: nptr): nptr; 220
algorithms and data structures_Page_220_Chunk4760
This book is licensed under a Creative Commons Attribution 3.0 License to copy a graph given by a pointer p to its origin, and return a pointer to the origin of the copy. Use the field cn, assuming that its initial value is 'nil' in every node of the original graph; set it to 'nil' in every node of the copy. Solution (a) function cptree(p: nptr): nptr; var cp: nptr; begin if p = nil then return(nil) else begin new(cp); cp^.e := p^.e; cp^.L := cptree(p^.L); cp^.R := cptree(p^.R); return(cp) end end; (b) function cpgraph(p: nptr): nptr; var cp: nptr; begin if p = nil then return(nil) elsif p^.cn ≠ nil then { node has already been copied } return(p^.cn) else begin new(cp); p^.cn := cp; cp^.cn := nil; cp^.e := p^.e; cp^.L := cpgraph(p^.L); cp^.R := cpgraph(p^.R); return(cp) end end; Exercise: list copying with constant auxiliary memory Consider binary trees as in part (a) of the preceding exercise. Memory for the stack implied by the recursion can be saved by writing an iterative tree copying procedure that uses only a constant amount of auxiliary memory. This requires a trick, as any depth-first traversal must be able to back up from the leaves toward the root. In the triple- tree traversal procedure, the return path is temporarily encoded in the tree being traversed. This idea can again be used here, but there is a simpler solution: The return path is temporarily encoded in the R-fields of the copy; the L- fields of certain nodes of the copy point back to the corresponding node in the original. Work out the details of a tree-copying procedure that works with O(1) auxiliary memory. Exercise: traversing a directed acyclic graph A directed graph consists of nodes and directed arcs, where each arc leads from one node to another. A directed graph is acyclic if the arcs form no cycles. One way to ensure that a graph is acyclic is to label nodes with distinct integers and to draw each arc from a lower number to a higher number. Consider a binary directed acyclic graph, where each node has two pointer fields, L and R, to represent at most two arcs that lead out of that node. An example is shown in Exhibit 21.13. Exhibit 21.13: A rooted acyclic graph. Algorithms and Data Structures 221 A Global Text
algorithms and data structures_Page_221_Chunk4761
21. List structures (a) Write a program to visit every node in a directed acyclic graph reachable from a pointer called 'root'. You are free to execute procedure 'visit' for each node as often as you like. (b) Write a program similar to (a) where you are required to execute procedure 'visit' exactly once per node. Hint: Nodes may need to have additional fields. Exercise: counting nodes on a square grid Consider a network superimposed on a square grid: each node is connected to at most four neighbors in the directions east, north, west, south (Exhibit 21.14): type nptr = ^node; node = record E, N, W, S: nptr; status: boolean end; var origin: nptr; Exhibit 21.14: A graph embedded in a square grid. A 'nil' pointer indicates the absence of a neighbor. Neighboring nodes are doubly linked: if a pointer in node p points to node q, the reverse pointer of q points to p; (e.g., p^.W = q and q^.E = p). The pointer 'origin' is 'nil' or points to a node. Consider the problem of counting the number of nodes that can be reached from 'origin'. Assume that the status field of all nodes is initially set to false. How do you use this field? Write a function nn(p: nptr): integer; to count the number of nodes. Solution function nn(p: nptr): integer; begin if p = nil cor p^.status then return(0) else begin p^.status:= true; return(1 + nn(p^.E) + nn(p^.N) + nn(p^.W) + nn(p^.S)) end end; Exercise: counting nodes in an arbitrary network We generalize the problem above to arbitrary directed graphs, such as that of Exhibit 21.15, where each node may have any number of neighbors. This graph is represented by a data structure defined by Exhibit 21.16 and the type definitions below. Each node is linked to an arbitrary number of other nodes. Exhibit 21.15: An arbitrary (cyclic) directed graph. 222
algorithms and data structures_Page_222_Chunk4762
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 21.16: A possible implementation as a list structure. type nptr = ^node; cptr = ^cell; node = record status: boolean; np: nptr; cp: cptr end; cell = record np: nptr; cp: cptr end; var origin: nptr; The pointer 'origin' has the value 'nil' or points to a node. Consider the problem of counting the number n of nodes that can be reached from 'origin'. The status field of all nodes is initially set to false. How do you use it? Write a function nn(p: nptr): integer; that returns n. Binary search trees A binary search tree is a binary tree T where each node N stores a data element e(N) from a domain X on which a total order ≤ is defined, subject to the following order condition: For every node N in T, all elements in the left subtree L(N) of N are < e(N), and all elements in the right subtree R(N) of N are > e(N). Let x1, 2, … , xn be n elements drawn from the domain X. Definition: A binary search tree for x1, x2, … , xn is a binary tree T with n nodes and a one-to-one mapping between the n given elements and the n nodes, such that ∀ N in T ∀ N' ∈ L(N) ∀ N" ∈ R(N): e(N') < e(N) < e(N") Exercise Show that the following statement is equivalent to this order condition: The inorder traversal of the nodes of T coincides with the natural order < of the elements assigned to the nodes. Remark: The order condition can be relaxed to e(N') ≤ e(N) < e(N") to accommodate multiple occurrences of the same value, with only minor modifications to the statements and algorithms presented in this section. For simplicity's sake we assume that all values in a tree are distinct. The order condition permits binary search and thus guarantees a worst-case search time O(h) for a tree of height h. Trees that are well balanced (in an intuitive sense; see the next section for a definition), that have not degenerated into linear lists, have a height h = O(log n) and thus support search in logarithmic time. Algorithms and Data Structures 223 A Global Text
algorithms and data structures_Page_223_Chunk4763
21. List structures Basic operations on binary search trees are most easily implemented as recursive procedures. Consider a tree represented as in the preceding section, with empty subtrees denoted by 'nil'. The following function 'find' searches for an element x in a subtree pointed to by p. It returns a pointer to a node containing x if the search is successful, and 'nil' if it is not. function find(x: elt; p: nptr): nptr; begin if p = nil then return(nil) elsif x < p^.e then return(find(x, p^.L)) elsif x > p^.e then return(find(x, p^.R)) else { x = p^.e } return(p) end; The following procedure 'insert' leaves the tree alone if the element x to be inserted is already stored in the tree. The parameter p initially points to the root of the subtree into which x is to be inserted. procedure insert(x: elt; var p: nptr); begin if p = nil then { new(p); p^.e := x; p^.L := nil; p^.R := nil } elsif x < p^.e then insert(x, p^.L) elsif x > p^.e then insert(x, p^.R) end; Initial call: insert(x, root); To delete an element x, we first have to find the node N that stores x. If this node is a leaf or semileaf (a node with only one subtree), it is easily deleted; but if it has two subtrees, it is more efficient to leave this node in place and to replace its element x by an element found in a leaf or semileaf node, and delete the latter (Exhibit 21.17). Thus we distinguish three cases: 1. If N has no child, remove N. 2. If N has exactly one child, replace N by this child node. 3. If N has two children, replace x by the largest element y in the left subtree, or by the smallest element z in the right subtree of N. Either of these elements is stored in a node with at most one child, which is removed as in case (1) or (2). 224
algorithms and data structures_Page_224_Chunk4764
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 21.17: Element x is deleted while preserving its node N. Node N is filled with a new value y, whose old node is easier to delete. A sentinel is again the key to an elegant iterative implementation of binary search trees. In a node with no left or right child, the corresponding pointer points to the sentinel. This sentinel is a node that contains no element; its left pointer points to the root and its right pointer points to itself. The root, if it exists, can only be accessed through the left pointer of the sentinel. The empty tree is represented by the sentinel alone (Exhibit 21.18). A typical tree is shown in Exhibit 21.19. Exhibit 21.18: The empty binary tree is represented by the sentinel which points to itself. Exhibit 21.19: A binary tree implemented as a list structure with sentinel. The following implementation of a dictionary as a binary search tree uses a sentinel accessed via the variable d: type nptr = ^node; node = record e: elt; L, R: nptr end; dictionary = nptr; procedure create(var d: dictionary); begin {create sentinel } new(d); d^.L := d; d^.R := d end; Algorithms and Data Structures 225 A Global Text
algorithms and data structures_Page_225_Chunk4765
21. List structures function member(d: dictionary; x: elt): boolean; var p: nptr; begin d^.e := x; { initialize element in sentinel } p := d^.L; { point to root, if it exists } while x ≠ p^.e do if x < p^.e then p := p^.L else { x > p^.e } p := p^.R; return(p ≠ d) end; Procedure 'find' searches for x. If found, p points to the node containing x, and q to its parent. If not found, p points to the sentinel and q to the parent-to-be of a new node into which x will be inserted. procedure find(d: dictionary; x: elt; var p, q: nptr); begin d^.e := x; p := d^.L; q := d; while x ≠ p^.e do begin q := p; if x < p^.e then p := p^.L else { x > p^.e } p := p^.R end end; procedure insert(var d: dictionary; x: elt); var p, q: nptr; begin find(d, x, p, q); if p = d then begin { x is not yet in the tree } new(p); p^.e := x; p^.L := d; p^.R := d; if x ≤ q^.e then q^.L := p else { x > q^.e } q^.R := p end end; procedure delete(var d: dictionary; x: elt); var p, q, t: nptr; begin find(d, x, p, q); if p ≠ d then { x has been found } if (p^.L ≠ d) and (p^.R ≠ d) then begin { p has left and right children; find largest element in left subtree } t := p^.L; q:= p; while t^.R ≠ d do { q := t; t := t^.R }; if t^.e < q^.e then q^.L := t^.L else { t^.e > q^.e } q^.R := t^.L p^.e := t^.e; end else begin { p has at most one child } if p^.L ≠ d then{ left child only } p := p^.L elsif p^.R ≠ d then{ right child only } p := p^.R else { p has no children }p := d; if x ≤ q^.e then q^.L := p else { x > q^.e } q^.R := p end end; In the best case of a completely balanced binary search tree for n elements, all leaves are on levels [log2 n] or [log2 n]– 1, and the search tree has the height [log2 n]. The cost for performing the 'member', 'insert', or 'delete' operation is bounded by the longest path from the root to a leaf (i.e. the height of the tree) and is therefore O(log n). 226
algorithms and data structures_Page_226_Chunk4766
This book is licensed under a Creative Commons Attribution 3.0 License Without any further provisions, a binary search tree can degenerate into a linear list in the worst case. Then the cost for each of the operations would be O(n). What is the expected average cost for the search operation in a randomly generated binary search tree? "Randomly generated" means that each permutation of the n elements to be stored in the binary search tree has the same probability of being chosen as the input sequence. Furthermore, we assume that the tree is generated by insertions only. Therefore, each of the n elements is equally likely to be chosen as the root of the tree. Let pn be the expected path length of a randomly generated binary search tree storing n elements. Then As shown in chapter 16 in the section “Recurrence relations”, this recurrence relation has the solution Since the average search time in randomly generated binary search trees, measured in terms of the number of nodes visited, is pn / n and ln 4 ≈ 1.386, it follows that the cost is O(log n) and therefore only about 40 per cent higher than in the case of completely balanced binary search trees. Balanced trees: general definition If insertions and deletions occurred at random, and the assumption of the preceding section was realistic, we could let search trees grow and shrink as they please, incurring a modest increase of 40 per cent in search time over completely balanced trees. But real data are not random: they are typically clustered, and long runs of monotonically increasing or decreasing elements occur, often as the result of a previous processing step. Unfortunately, such deviation from randomness degrades the performance of search trees. To prevent search trees from degenerating into linear lists, we can monitor their shape and restructure them into a more balanced shape whenever they have become too skewed. Several classes of balanced search trees guarantee that each operation 'member', 'insert', and 'delete' can be performed in time O(log n) in the worst case. Since the work to be done depends directly on the height of the tree, such a class B of search trees must satisfy the following two conditions (hT is the height of a tree T, nT is the number of nodes in T): Balance condition: ∃c > 0 ∀ T ∀ B: hT ≤ c · log2 nT Rebalancing condition: If an 'insert' or 'delete' operation, performed on a tree T ∈ B, yields a tree T' ∉ B, it must be possible to rebalance T' in time O(log n) to yield a tree T" ∈ B. Example: almost complete trees The class of almost complete binary search trees satisfies the balance condition but not the restructuring condition. In the worst case it takes time O(n) to restructure such a binary search tree (Exhibit 21.20), and if 'insert' and 'delete' are defined to include any rebalancing that may be necessary, these operations cannot be guaranteed to run in time O(log n). Algorithms and Data Structures 227 A Global Text
algorithms and data structures_Page_227_Chunk4767
21. List structures Exhibit 21.20: Restructuring: worst case In the next two sections we present several classes of balanced trees that meet both conditions: the height- balanced or AVL-trees (G. Adel'son-Vel'skii and E. Landis, 1962) [AL 62] and various multiway trees, such as B- trees [BM 72, Com 79] and their generalization, (a,b)-trees [Meh 84a]. AVL-trees, with their small nodes that hold a single data element, are used primarily for storing data in main memory. Multiway trees, with potentially large nodes that hold many elements, are also useful for organizing data on secondary storage devices, such as disks, that allow direct access to sizable physical data blocks. In this case, a node is typically chosen to fill a physical data block, which is read or written in one access operation. Height-balanced trees Definition: A binary tree is height-balanced if, for each node, the heights of its two subtrees differ by at most one. Height-balanced search trees are also called AVL-trees. Exhibit 21.21 to Exhibit 21.23 show various AVL-trees, and one that is not. Exhibit 21.21: Examples of height-balanced trees Exhibit 21.22: Example of a tree not height-balanced;the marked node violates the balance condition. A "most-skewed" AVL-tree Th is an AVL-tree of height h with a minimal number of nodes. Starting with T 0 and T1 shown in Exhibit 21.23, Th is obtained by attaching Th–1 and Th–2 as subtrees to a new root. 228
algorithms and data structures_Page_228_Chunk4768
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 21.23: Most skewed AVL trees of heights h = 0 through h = 4 The number of nodes in a most-skewed AVL-tree of height h is given by the recurrence relation nh = nh–1 + nh–2 + 1, n0 = 1, n1 = 2. In the section on recurrence relations in the chapter entitled “The mathematics of algorithm analysis”, it has been shown that the recurrence relation mh = mh–1 + mh–2, m0 = 0, m1 = 1 has the solution Since nh = mh+3 – 1 we obtain Since it follows that and therefore nh behaves asymptotically as Algorithms and Data Structures 229 A Global Text
algorithms and data structures_Page_229_Chunk4769
21. List structures Applying the logarithm results in Therefore, the height of a worst-case AVL-tree with n nodes is about 1.44 · log2 n. Thus the class of AVL-trees satisfies the balance condition, and the 'member' operation can always be performed in time O(log n). We now show that the class of AVL-trees also satisfies the rebalancing condition. Thus AVL-trees support insertion and deletion in time O(log n). Each node N of an AVL-tree has one of the balance properties / (left- leaning), \ (right-leaning), or – (horizontal), depending on the relative height of its two subtrees. Two local tree operations, rotation and double rotation, allow the restructuring of height-balanced trees that have been disturbed by an insertion or deletion. They split a tree into subtrees and rebuild it in a different way. Exhibit 21.24 shows a node, marked black, that got out of balance, and how a local transformation builds an equivalent tree (for the same elements, arranged in order) that is balanced. Each of these transformations has a mirror image that is not shown. The algorithms for insertion and deletion use these rebalancing operations as described below. Exhibit 21.24: Two local rebalancing operations Insertion A new element is inserted as in the case of a binary search tree. The balance condition of the new node becomes – (horizontal). Starting at the new node, we walk toward the root of the tree, passing along the message that the height of the subtree rooted at the current node has increased by one. At each node encountered along this path, an operation determined by the following rules is performed. These rules depend on the balance condition of the node before the new element was inserted, and on the direction from which the node was entered (i.e. from its left or right child). 230
algorithms and data structures_Page_230_Chunk4770
This book is licensed under a Creative Commons Attribution 3.0 License Rule I1: If the current node has balance condition –, change it to / or \ depending on whether we entered from the node's left or from its right child. If the current node is the root, terminate; if not, continue to follow the path upward. Rule I2: If the current node has balance condition / or \ and is entered from the subtree that was previously shorter, change the balance condition to—and terminate (the height of the subtree rooted at the current node has not changed). Rule I3: If the current node has balance condition / or \ and is entered from the subtree that was previously taller, the balance condition of the current node is violated and gets restored as follows: (a) If the last two steps were in the same direction (both from left children, or both from right children), an appropriate rotation restores all balances and the procedure terminates. (b) If the last two steps were in opposite directions (one from a left child, the other from a right child), an appropriate double rotation restores all balances and the procedure terminates. The initial insertion travels along a path from the root to a leaf, and the rebalancing process travels back up along the same path. Thus the cost of an insertion in an AVL-tree is O(h), or O(log n) in the worst case. Notice that an insertion calls for at most one rotation or double rotation, as shown in the example in Exhibit 21.25. Example Insert 1, 2, 5, 3, 4, 6, 7 into an initially empty AVL-tree (Exhibit 21.25). The balance condition of a node is shown below it. Boldfaced nodes violate the balance condition. Algorithms and Data Structures 231 A Global Text
algorithms and data structures_Page_231_Chunk4771
21. List structures Exhibit 21.25: Trace of consecutive insertions and the rebalancings they trigger Deletion An element is deleted as in the case of a binary search tree. Starting at the parent of the deleted node, walk towards the root, passing along the message that the height of the subtree rooted at the current node has decreased by one. At each node encountered, perform an operation according to the following rules. These rules depend on the balance condition of the node before the deletion and on the direction from which the current node and its child were entered. Rule D1: If the current node has balance condition –, change it to \ or / depending on whether we entered from the node's left or from its right child, and terminate (the height of the subtree rooted at the current node has not changed). Rule D2: If the current node has balance condition / or \ and is entered from the subtree that was previously taller, change the balance condition to – and continue upward, passing along the message that the subtree rooted at the current node has been shortened. Rule D3: If the current node has balance condition / or \ and is entered from the subtree that was previously shorter, the balance condition is violated at the current node. We distinguish three subcases according to the 232
algorithms and data structures_Page_232_Chunk4772
This book is licensed under a Creative Commons Attribution 3.0 License balance condition of the other child of the current node (consider also the mirror images of the following illustrations): (a) X Y Z a b X Y Z b a rotation An appropriate rotation restores the balance of the current node without changing the height of the subtree rooted at this node. Terminate. (b) X Y Z b a X Y Z a b rotation A rotation restores the balance of the current node. Continue upward, passing along the message that the subtree rooted at the current node has been shortened. (c) double rotation W a b c a b c X Y Z W X Y Z A double rotation restores the balance of the current node. Continue upward, passing along the message that the subtree rooted at the current node has been shortened. Similar transformations apply if either X or Y, but not both, are one level shorter than shown in this figure. If so, the balance conditions of some nodes differ from those shown, but this has no influence on the total height of the subtree. In contrast to insertion, deletion may require more than one rotation or double rotation to restore all balances. Since the cost of a rotation or double rotation is constant, the worst-case cost for rebalancing the tree depends only on the height of the tree, and thus the cost of a deletion in an AVL-tree is O(log n) in the worst case. Multiway trees Nodes in a multiway tree may have a variable number of children. As we are interested in balanced trees, we add two restrictions. First, we insist that all leaves (the nodes without children) occur at the same depth. Second, we constrain the number of children of all internal nodes by a lower bound a and an upper bound b. Many varieties of multiway trees are known; they differ in details, but all are based on similar ideas. For example, (2,3)-trees are defined by the requirement that all internal nodes have either two or three children. We generalize this concept and discuss (a,b)-trees. Definition: Consider a domain X on which a total order ≤ is defined. Let a and b be integers with 2 ≤ a and 2 · a – 1 ≤ b. Let c(N) denote the number of children of node N. An (a,b)-tree is an ordered tree with the following properties: Algorithms and Data Structures 233 A Global Text
algorithms and data structures_Page_233_Chunk4773
21. List structures • All leaves are at the same level • 2 ≤ c(root) ≤ b • For all internal nodes N except the root, a ≤ c(N) ≤ b A node with k children contains k – 1 elements x1 < x2 < … < xk–1 drawn from X; the subtrees corresponding to the k children are denoted by T1, T2, … , Tk. An (a,b)-tree supports "c(N) search" in the same way that a binary tree supports binary search, thanks to the following order condition: • y ≤ xi for all elements y stored in subtrees T1, … , Ti • xi < z for all elements z stored in subtrees Ti+1, … , Tk Definition: (a,b)-trees with b = 2 · a – 1 are known as B-trees [BM 72, Com 79]. The algorithms we discuss operate on internal nodes, shown in white in Exhibit 21.26, and ignore the leaves, shown in black. For the purpose of understanding search and update algorithms, leaves can be considered fictitious entities used only for counting. In practice, however, things are different. The internal nodes merely constitute a directory to a file that is stored in the leaves. A leaf is typically a physical storage unit, such as a disk block, that holds all the records whose key values lie between two (adjacent) elements stored in internal nodes. Exhibit 21.26: Example of a (3,5)-tree The number n of elements stored in the internal nodes of an (a,b)-tree of height h is bounded by and thus this shows that the class of (a,b)-trees satisfies the balance condition h = O(log n). We show that this class also meets the rebalancing condition, namely, that (a,b)-trees support insertion and deletion in time O(log n). Insertion Insertion of a new element x begins with a search for x that terminates unsuccessfully at a leaf. Let N be the parent node of this leaf. If N contained fewer than b – 1 elements before the insertion, insert x into N and terminate. If N was full, we imagine b elements temporarily squeezed into the overflowing node N. Let m be the median of these b elements, and use m to split N into two: a left node NL populated by the (b – 1) / 2 elements smaller than m, and a right node NR populated by the (b – 1) / 2 elements larger than m. The condition 2 · a – 1 ≤ b ensures that (b – 1) / 2 ≥ a – 1, in other words, that each of the two new nodes contains at least a – 1 elements. The median element m is pushed upward into the parent node, where it serves as a separator between the two new nodes NL and NR that now take the place formerly inhabited by N. Thus the problem of insertion into a node at a given level is replaced by the same problem one level higher in the tree. The new separator element may be absorbed in a nonfull parent, but if the parent overflows, the splitting process described is repeated recursively. At 234
algorithms and data structures_Page_234_Chunk4774
This book is licensed under a Creative Commons Attribution 3.0 License worst, the splitting process propagates to the root of the tree, where a new root that contains only the median element is created. (a,b)-trees grow at the root, and this is the reason for allowing the root to have as few as two children. Deletion Deletion of an element x begins by searching for it. As in the case of binary search trees, deletion is easiest at the bottom of the tree, at a node of maximal depth whose children are leaves. If x is found at a higher level of the tree, in a node that has internal nodes as children, x is the separator between two subtrees T L and TR. We replace x by another element z, either the largest element in TL or the smallest element in TR, both of which are stored in a node at the bottom of the tree. After this exchange, the problem is reduced to deleting an element z from a node N at the deepest level. If deletion (of x or z) leaves N with at least a – 1 elements, we are done. If not, we try to restore N's occupancy condition by stealing an element from an adjacent sibling node M. If there is no sibling M that can spare an element, that is, if M is minimally occupied, M and N are merged into a single node L. L contains the a – 2 elements of N, the a – 1 elements of M, and the separator between M and N which was stored in their parent node, for a total of 2 · (a – 1) ≤ b – 1 elements. Since the parent (of the old nodes M and N, and of the new node L) lost an element in this merger, the parent may underflow. As in the case of insertion, this underflow can propagate to the root and may cause its deletion. Thus (a,b)-trees grow and shrink at the root. Both insertion and deletion work along a single path from the root down to a leaf and (possibly) back up. Thus their time is bounded by O(h), or equivalently, by O(log n): (a,b)-trees can be rebalanced in logarithmic time. Amortized cost. The performance of (a,b)-trees is better than the worst-case analysis above suggests. It can be shown that the total cost of any sequence of s insertions and deletions into an initially empty (a,b)-tree is linear in the length s of the sequence: whereas the worst-case cost of a single operation is O(log n), the amortized cost per operation is O(1) [Meh 84a]. Amortized cost is a complexity measure that involves both an average and a worst-case consideration. The average is taken over all operations in a sequence; the worst case is taken over all sequences. Although any one operation may take time O(log n), we are guaranteed that the total of all s operations in any sequence of length s can be done in time O(s), as if each single operation were done in time O(1). Exhibit 21.27: A slightly skewed (3,5)-tree. Exercise: insertion and deletion in a (3,5)-tree Starting with the (3,5)-tree shown in Exhibit 21.27, perform the sequence of operations: insert 38, delete 10, delete 12, delete 50. Draw the tree after each operation. Solution Inserting 38 causes a leaf and its parent to split (Exhibit 21.28). Deleting 10 causes underflow, remedied by borrowing an element from the left sibling (Exhibit 21.29). Deleting 12 causes underflow in both a leaf and its parent, remedied by merging (Exhibit 21.30). Deleting 50 causes merging at the leaf level and borrowing at the parent level (Exhibit 21.31). Algorithms and Data Structures 235 A Global Text
algorithms and data structures_Page_235_Chunk4775
21. List structures Exhibit 21.28: Node splits propagate towards the root Exhibit 21.29: A deletion is absorbed by borrowing Exhibit 21.30: Another deletion propagates node merges towards the root Exhibit 21.31: Node merges and borrowing combined (2,3)-trees are the special case a = 2, b = 3: each node has two or three children. Exhibit 21.32 omits the leaves. Starting with the tree in state 1 we insert the value 9: the rightmost node at the bottom level overflows and splits, the median 8 moves up into the parent. The parent also overflows, and the median 6 generates a new root (state 2). The deletion of 1 is absorbed without any rebalancing (state 3). The deletion of 2 causes a node to underflow, remedied by stealing an element from a sibling: 2 is replaced by 3 and 3 is replaced by 4 (state 4). The deletion of 3 236
algorithms and data structures_Page_236_Chunk4776
This book is licensed under a Creative Commons Attribution 3.0 License triggers the merger of the nodes assigned to 3 and 5; this causes an underflow in their parent, which in turn propagates to the root and results in a tree of reduced height (state 5). Exhibit 21.32: Tracing insertions and deletions in a (2,3)-tree As mentioned earlier, multiway trees are particularly useful for managing data on a disk. If each node is allocated to its own disk block, searching for a record triggers as many disk accesses as there are levels in the tree. The depth of the tree is minimized if the maximal fan-out b is maximized. We can pack more elements into a node by shrinking their size. As the records to be stored are normally much larger than their identifying keys, we store keys only in the internal nodes and store entire records in the leaves (which we had considered to be empty until now). Thus the internal nodes serve as an index that assigns to a key value the path to the corresponding leaf. Exercises and programming projects 1. Design and implement a list structure for storing a sparse matrix. Your implementation should provide procedures for inserting, deleting, changing, and reading matrix elements. 2. Implement a fifo queue by a circular list using only one external pointer f and a sentinel. f always points to the sentinel and provides access to the head and tail of the queue. 3. Implement a double-ended queue (deque) by a doubly linked list. 4. Binary search trees and sorting A binary search tree given by the following declarations is used to manage a set of integers: type nptr = ^node node = record L, R: nptr; x: integer end; var root: nptr; The empty tree is represented as root = nil. (a) Draw the result of inserting the sequence 6, 15, 4, 2, 7, 12, 5, 18 into the empty tree. Algorithms and Data Structures 237 A Global Text
algorithms and data structures_Page_237_Chunk4777
21. List structures (b) Write a procedure smallest(var x: integer); which returns the smallest number stored in the tree, and a procedure remove smallest; which deletes it. If the tree is empty both procedures should call a procedure message('tree is empty'); (c) Write a procedure sort; that sorts the numbers stored in var a: array[1 .. n] of integer; by inserting the numbers into a binary search tree, then writing them back to the array in sorted order as it traverses the tree. (d) Analyze the asymptotic time complexity of 'sort' in a typical and in the worst case. (e) Does this approach lead to a sorting algorithm of time complexity Θ (ν • λογ ν) 5. Extend the implementation of a dictionary as a binary search tree in the “Binary search trees” section to support the operations 'succ' and 'pred' as defined in chapter 19 in the section “Dictionary”. 6. Insertion and deletion in AVL-trees: Starting with an empty AVL-tree, insert 1, 2, 5, 6, 7, 8, 9, 3, 4, in this order. Draw the AVL-tree after each insertion. Now delete all elements in the opposite order of insertion (i.e. in last-in-first-out order). Does the AVL-tree go through the same states as during insertion but in reverse order? 7. Implement an AVL-tree supporting the dictionary operations 'insert', 'delete', 'member', 'pred', and 'succ'. 8. Explain how to find the smallest element in an (a,b)-tree and how to find the predecessor of a given element in an (a,b)-tree. 9. Implement a dictionary as a B-tree. 238
algorithms and data structures_Page_238_Chunk4778
This book is licensed under a Creative Commons Attribution 3.0 License 22. Address computation Learning objectives: • hashing • perfect hashing • collision resolution methods: separate chaining, coalesced chaining, open addressing (linear probing and double hashing) • deletions degrade performance of a hash table • Performance does not depend on the number of data elements stored but on the load factor of the hash table. • randomization: transform unknown distribution into a uniform distribution • Extendible hashing uses a radix tree to adapt the address range dynamically to the contents to be stored; deletions do not degrade performance. • order-preserving extendible hashing Concepts and terminology The term address computation (also hashing, hash coding, scatter storage, or key-to-address transformations) refers to many search techniques that aim to assign an address of a storage cell to any key value x by means of a formula that depends on x only. Assigning an address to x independently of the presence or absence of other key values leads to faster access than is possible with the comparative search techniques discussed in earlier chapters. Although this goal cannot always be achieved, address computation does provide the fastest access possible in many practical situations. We use the following concepts and terminology (Exhibit 22.1). The home address a of x is obtained by means of a hash function h that maps the key domain X into the address space A [i.e. a = h(x)]. The address range is A = {0, 1, … , m – 1}, where m is the number of storage cells available. The storage cells are represented by an array T[0 .. m – 1], the hash table; T[a] is the cell addressed by a ∈ A. T[h(x)] is the cell where an element with key value x is preferentially stored, but alas, not necessarily. Exhibit 22.1: The hash function h maps a (typically large) key domain X into a (much smaller) address space A. Algorithms and Data Structures 239 A Global Text
algorithms and data structures_Page_239_Chunk4779
22. Address computation Each cell has a capacity of b > 0 elements; b stands for bucket capacity. The number n of elements to be stored is therefore bounded by m · b. Two cases are usefully distinguished, depending on whether the hash table resides on disk or in central memory: 1. Disk or other secondary storage device: Considerations of efficiency suggest that a bucket be identified with a physical unit of transfer, typically a disk block. Such a unit is usually large compared to the size of an element, and thus b > 1. 2. Main memory: Cell size is less important, but the code is simplest if a cell can hold exactly one element (i.e. b = 1). For simplicity of exposition we assume that b = 1 unless otherwise stated; the generalization to arbitrary b is straightforward. The key domain X is normally much larger than the number n of elements to be stored and the number m of available cells T[a]. For example, a table used for storing a few thousand identifiers might have as its key domain the set of strings of length at most 10 over the alphabet {'a', 'b', … , 'z', '0', … , '9'}; its cardinality is close to 36 10. Thus in general the function h is many-to-one: Different key values map to the same address. The content to be stored is a sample from the key domain: It is not under the programmer's control and is usually not even known when the hash function and table size are chosen. Thus we must expect collisions, that is, events where more than b elements to be stored are assigned the same address. Collision resolution methods are designed to handle this case by storing some of the colliding elements elsewhere. The more collisions that occur, the longer the search time. Since the number of collisions is a random event, the search time is a random variable. Hash tables are known for excellent average performance and for terrible worst-case performance, which, one hopes, will never occur. Address computation techniques support the operations 'find' and 'insert' (and to a lesser extent also 'delete') in expected time O(1). This is a remarkable difference from all other data structures that we have discussed so far, in that the average time complexity does not depend on the number n of elements stored, but on the load factor λ = n / (m · b), or, for the special case b = 1: λ = n / m. Note that 0 ≤ λ ≤ 1. Before we consider the typical case of a hash table, we illustrate these concepts in two special cases where everything is simple; these represent ideals rarely attainable. The special case of small key domains If the number of possible key values is less than or equal to the number of available storage cells, h can map X one-to-one into or onto A. Everything is simple and efficient because collisions never occur. Consider the following example: X = {'a', 'b', … , 'z'}, A = {0, … , 25} h(x) = ord(x) – ord('a'); that is, h('a') = 0, h('b') = 1, h('c') = 2, … , h('z') = 25. Since h is one-to-one, each key value x is implied by its address h(x). Thus we need not store the key values explicitly, as a single bit (present / absent) suffices: var T: array[0 .. 25] of boolean; function member(x): boolean; begin return(T[h(x)]) end; 240
algorithms and data structures_Page_240_Chunk4780
This book is licensed under a Creative Commons Attribution 3.0 License procedure insert(x); begin T[h(x)] := true end; procedure delete(x); begin T[h(x)] := false end; The idea of collision-free address computation can be extended to large key domains through a combination of address computation and list processing techniques, as we will see in the chapter "Metric data structures". The special case of perfect hashing: table contents known a priori Certain common applications require storing a set of elements that never changes. The set of reserved words of a programming language is an example; when the lexical analyzer of a compiler extracts an identifier, the first issue to be determined is whether this is a reserved word such as 'begin' or 'while', or whether it is programmer defined. The special case where the table contents are known a priori, and no insertions or deletions occur, is handled more efficiently by special-purpose data structures than by a general dictionary. If the elements x1, x2, … , xn to be stored are known before the hash table is designed, the underlying key domain is not as important as the set of actually occurring key values. We can usually find a table size m, not much larger than the number n of elements to be stored, and an easily evaluated hash function h that assigns to each xi a unique address from the address space {0, … , m – 1}. It takes some trial and error to find such a perfect hash function h for a given set of elements, but the benefit of avoiding collisions is well worth the effort—the code that implements a collision-free hash table is simple and fast. A perfect hash function works for a static table only—a single insertion, after h has been chosen, is likely to cause a collision and destroy the simplicity of the concept and efficiency of the implementation. Perfect hash functions should be generated automatically by a program. The following unrealistically small example illustrates typical approaches to designing a perfect hash table. The task gets harder as the number m of available storage cells is reduced toward the minimum possible, that is, the number n of elements to be stored. Example In designing a perfect hash table for the elements 17, 20, 24, 38, and 51, we look for arithmetic patterns. These are most easily detected by considering the binary representations of the numbers to be stored: 5 4 3 2 1 0 bit position 17 0 1 0 0 0 1 20 0 1 0 1 0 0 24 0 1 1 0 0 0 38 1 0 0 1 1 0 51 1 1 0 0 1 1 We observe that the least significant three bits identify each element uniquely. Therefore, the hash function h(x) = x mod 8 maps these five elements collision-free into the address space A = {0, … , 6}, with m = 7 and two empty cells. An attempt to further economize space leads us to observe that the bits in positions 1, 2, and 3, with weights 2, 4, and 8 in the binary number representation, also identify each element uniquely, while ranging over the address space of minimal size A = {0, … , 4}. The function h(x) = (x div 2) mod 8 extracts these three bits and assigns the following addresses: X: 17 20 24 38 51 A: 0 2 4 3 1 Algorithms and Data Structures 241 A Global Text
algorithms and data structures_Page_241_Chunk4781
22. Address computation A perfect hash table has to store each element explicitly, not just a bit (present/absent). In the example above, the elements 0, 1, 16, 17, 32, 33, … all map into address 0, but only 17 is present in the table. The access function 'member(x)' is implemented as a single statement: return ((h(x) ≤ 4) cand (T[h(x)] = x)); The boolean operator 'cand' used here is understood to be the conditional and: Evaluation of the expression proceeds from left to right and stops as soon as its value is determined. In our example, h(x) > 4 suffices to assign 'false' to the expression (h(x) ≤ 4) and (T[h(x)] = x). Thus the 'cand' operator guarantees that the table declared as: var T: array[0 .. 4] of element; is accessed within its index bounds. For table contents of realistic size it is impractical to construct a perfect hash function manually—we need a program to search exhaustively through the large space of functions. The more slack m – n we allow, the denser is the population of perfect functions and the quicker we will find one. [Meh 84a] presents analytical results on the complexity of finding perfect hash functions. Exercise: perfect hash tables Design several perfect hash tables for the content {3, 13, 57, 71, 82, 93}. Solution Designing a perfect hash table is like answering a question of the type: What is the next element in the sequence 1, 4, 9, … ? There are infinitely many answers, but some are more elegant than others. Consider: h 3 13 57 71 82 93 Address range (x div 3) mod 7 1 4 5 2 6 3 [1 .. 6] x mod 13 3 0 5 6 4 2 [0 .. 6] (x div 4) mod 8 0 3 6 1 4 7 [0 .. 7] if x = 71 then 4 else x mod 7 3 6 1 4 5 2 [1 .. 6] Conventional hash tables: collision resolution In contrast to the special cases discussed, most applications of address computation present the data structure designer with greater uncertainties and less favorable conditions. Typically, the underlying key domain is much larger than the available address range, and not much is known about the elements to be stored. We may have an upper bound on n, and we may know the probability distribution that governs the random sample of elements to be stored. In setting up a customer list for a local business, for example, the number of customers may be bounded by the population of the town, and the distribution of last names can be obtained from the telephone directory—many names will start with H and S, hardly any with Q and Y. On the basis of such information, but in ignorance of the actual table contents to be stored, we must choose the size m of the hash table and design the hash function h that maps the key domain X into the address space A= {0, … , m – 1}. We will then have to live with the consequences of these decisions, at least until we decide to rehash: that is, resize the table, redesign the hash function, and reinsert all the elements that we have stored so far. Later sections present some pragmatic advice on the choice of h; for now, let us assume that an appropriate hash function is available. Regardless of how smart a hash function we have designed, collisions (more than b elements share the same home address of a bucket of capacity b) are inevitable in practice. Thus hashing requires techniques 242
algorithms and data structures_Page_242_Chunk4782
This book is licensed under a Creative Commons Attribution 3.0 License for handling collisions. We present the three major collision resolution techniques in use: separate chaining, coalesced chaining, and open addressing. The two techniques called chaining call upon list processing techniques to organize overflowing elements. Separate chaining is used when these lists live in an overflow area distinct from the hash table proper; coalesced chaining when the lists live in unused parts of the table. Open addressing uses address computation to organize overflowing elements. Each of these three techniques comes in different variations; we illustrate one typical choice. Separate chaining The memory allocated to the table is split into a primary and an overflow area. Any overflowing cell or bucket in the primary area is the head of a list, called the overflow chain, that holds all elements that overflow from that bucket. Exhibit 22.2 shows six elements inserted in the order x1, x2, … . The first arrival resides at its home address; later ones get appended to the overflow chain. Exhibit 22.2: Separate chaining handles collisions in a separate overflow area. Separate chaining is easy to understand: insert, delete, and search operations are simple. In contrast to other collision handling techniques, this hybrid between address computation and list processing has two major advantages: (1) deletions do not degrade the performance of the hash table, and (2) regardless of the number m of home addresses, the hash table will not overflow until the entire memory is exhausted. The size m of the table has a critical influence on the performance. If m « n, overflow chains are long and we have essentially a list processing technique that does not support direct access. If m » n, overflow chains are short but we waste space in the table. Even for the practical choice m ≈ n, separate chaining has some disadvantages: • Two different accessing techniques are required. • Pointers take up space; this may be a significant overhead for small elements. Algorithms and Data Structures 243 A Global Text
algorithms and data structures_Page_243_Chunk4783
22. Address computation • Memory is partitioned into two separate areas that do not share space: If the overflow area is full, the entire table is full, even if there is still space in the array of home cells. This consideration leads to the next technique. Coalesced chaining The chains that emanate from overflowing buckets are stored in the empty space in the hash table rather than in a separate overflow area (Exhibit 22.3). This has the advantage that all available space is utilized fully (except for the overhead of the pointers). However, managing the space shared between the two accessing techniques gets complicated. Exhibit 22.3: Coalesced chaining handles collisions by building lists that share memory with the hash table. The next technique has similar advantages (in addition, it incurs no overhead for pointers) and disadvantages; all things considered, it is probably the best collision resolution technique. Open addressing Assign to each element x ∈ X a probe sequence a0 = h(x), a1, a2, … of addresses that fills the entire address range A. The intention is to store x preferentially at a0, but if T[a0] is occupied then at a1, and so on, until the first empty cell is encountered along the probe sequence. The occupied cells along the probe sequence are called the collision path of x—note that the collision path is a prefix of the probe sequence. If we enforce the invariant: If x is in the table at T[a] and if i precedes a in the probe sequence for x, then T[i] is occupied. The following fast and simple loop that travels along the collision path can be used to search for x: a := h(x); while T[a] ≠ x and T[a] ≠ empty do a := (next address in probe sequence); Let us work out the details so that this loop terminates correctly and the code is as concise and fast as we can make it. The probe sequence is defined by formulas in the program (an example of an implicit data structure) rather than by pointers in the data as is the case in coalesced chaining. Example: linear probing ai+1 = (ai + 1) mod m is the simplest possible formula. Its only disadvantage is a phenomenon called clustering. Clustering arises when the collision paths of many elements in the table overlap to a large extent, as is likely to happen in linear probing. Once elements have collided, linear probing will store them in consecutive cells. All elements that hash into this block of contiguous occupied cells travel along the same collision path, thus 244
algorithms and data structures_Page_244_Chunk4784
This book is licensed under a Creative Commons Attribution 3.0 License lengthening this block; this in turn increases the probability that future elements will hash into this block. Once this positive feedback loop gets started, the cluster keeps growing. Double hashing is a special type of open addressing designed to alleviate the clustering problem by letting different elements travel with steps of different size. The probe sequence is defined by the formulas a0 = h(x), δ = g(x) > 0, ai+1 = (ai + δ ) mod m, m prime g is a second hash function that maps the key space X into [1 .. m – 1]. Two important important details must be solved: • The probe sequence of each element must span the entire address range A. This is achieved if m is relatively prime to every step size δ, and the easiest way to guarantee this condition is to choose m prime. • The termination condition of the search loop above is: T[a] = x or T[a] = empty. An unsuccessful search (x not in the table) can terminate only if an address a is generated with T[a] = empty. We have already insisted that each probe sequence generates all addresses in A. In addition, we must guarantee that the table contains at least one empty cell at all times—this serves as a sentinel to terminate the search loop. The following declarations and procedures implement double hashing. We assume that the comparison operators = and ≠ are defined on X, and that X contains a special value 'empty', which differs from all values to be stored in the table. For example, a string of blanks might denote 'empty' in a table of identifiers. We choose to identify an unsuccessful search by simply returning the address of an empty cell. const m = … ; { size of hash table - must be prime! } empty = … ; type key = … ; addr = 0 .. m – 1; step = 1 .. m – 1; var T: array[addr] of key; n: integer; { number of elements currently stored in T } function h(x: key): addr; { hash function for home address } function g(x: key): step; { hash function for step } procedure init; var a: addr; begin n := 0; for a := 0 to m – 1 do T[a] := empty end; function find(x: key): addr; var a: addr; d: step; begin a := h(x); d := g(x); while (T[a] ≠ x) and (T[a] ≠ empty) do a := (a + d) mod m; return(a) end; function insert(x: key): addr; var a: addr; d: step; begin a := h(x); d := g(x); while T[a] ≠ empty do begin if T[a] = x then return(a); a := (a + d) mod m end; if n < m – 1 then { n := n + 1; T[a] := x } else err- msg('table is full'); Algorithms and Data Structures 245 A Global Text
algorithms and data structures_Page_245_Chunk4785
22. Address computation return(a) end; Deletion of elements creates problems, as is the case in many types of hash tables. An element to be deleted cannot simply be replaced by 'empty', or else it might break the collision paths of other elements still in the table— recall the basic invariant on which the correctness of open addressing is based. The idea of rearranging elements in the table so as to refill a cell that was emptied but needs to remain full is quickly abandoned as too complicated—if deletions are numerous, the programmer ought to choose a data structure that fully supports deletions, such as balanced trees implemented as list structures. A limited number of deletions can be accommodated in an open address hash table by using the following technique. At any time, a cell is in one of three states: • empty (was never occupied, the initial state of all cells) • occupied (currently) • deleted (used to be occupied but is currently free) A cell in state 'empty' terminates the find loop; a cell in state 'empty' or in state 'deleted' terminates the insert loop. The state diagram shown in Exhibit 22.4 describes the transitions possible in the lifetime of a cell. Deletions degrade the performance of a hash table, because a cell, once occupied, never returns to the virgin state 'empty' which alone terminates an unsuccessful find. Even if an equal number of insertions and deletions keeps a hash table at a low load factor λ, unsuccessful finds will ultimately scan the entire table, as all cells drift into one of the states 'occupied' or 'deleted'. Before this occurs, the table ought to be rehashed; that is, the contents are inserted into a new, initially empty table. Exhibit 22.4: This state diagram describes possible life cycles of a cell: Once occupied, a cell will never again be as useful as an empty cell. Exercise: hash table with deletions Modify the program above to implement double hashing with deletions. Choice of hash function: randomization In conventional terminology, hashing is based on the concept of randomization. The purpose of randomizing is to transform an unknown distribution over the key domain X into a uniform distribution, and to turn consecutive samples that may be dependent into independent samples. This task appears to call for magic, and indeed, there is little or no mathematics that applies to the construction of hash functions; but there are commonsense observations worth remembering. These observations are primarily "don'ts". They stem from properties that sets of elements we wish to store frequently possess, and thus are based on some knowledge about the populations to be stored. If we assumed strictly nothing about these populations, there would be little to say about hash functions: an order-preserving proportional mapping of X into A would be as good as any other function. But in practice it is not, as the following examples show. 246
algorithms and data structures_Page_246_Chunk4786
This book is licensed under a Creative Commons Attribution 3.0 License 1. A Fortran compiler might use a hash table to store the set of identifiers it encounters in a program being compiled. The rules of the language and human habits conspire to make this set a highly biased sample from the set of legal Fortran identifiers. Example: Integer variables begin with I, J, K, L, M, N; this convention is likely to generate a cluster of identifiers that begin with one of these letters. Example: Successive identifiers encountered cannot be considered independent samples: If X and Y have occurred, there is a higher chance for Z to follow than for WRKHG. Example: Frequently, we see sequences of identifiers or statement numbers whose character codes form arithmetic progressions, such as A1, A2, A3, … or 10, 20, 30, … . 2. All file systems require or encourage the use of naming conventions, so that most file names begin or end with one of just a few prefixes or suffixes, such as ···.SYS, ···.BAK, ···.OBJ. An individual user, or a user community, is likely to generate additional conventions, so that most file names might begin, for example, with the initials of the names of the people involved. The files that store this text, for example, are structured according to 'part' and 'chapter', so we are currently in file P5 C22. In some directories, file names might be sorted alphabetically, so if they are inserted into a table in order, we process a monotonic sequence. The purpose of a hash function is to break up all regularities that might be present in the set of elements to be stored. This is most reliably achieved by "hashing" the elements, a word for which the dictionary offers the following explanations: (1) from the French hache, "battle-ax"; (2) to chop into small pieces; (3) to confuse, to muddle. Thus, to approximate the elusive goal of randomization, a hash function destroys patterns, including, unfortunately, the order < defined on X. Hashing typically proceeds in two steps. 1. Convert the element x into a number #(x). In most cases #(x) is an integer, occasionally, it is a real number 0 ≤ #(x) < 1. Whenever possible, this conversion of x into #(x) involves no action at all: The representation of x, whatever type x may be, is reinterpreted as the representation of the number #(x). When x is a variable-length item, for example a string, the representation of x is partitioned into pieces of suitable length that are "folded" on top of each other. For example, the four-letter word x = 'hash' is encoded one letter per byte using the 7-bit ASCII code and a leading 0 as 01101000 01100001 01110011 01101000. It may be folded to form a 16-bit integer by exclusive-or of the leading pair of bytes with the trailing pair of bytes: 0110100001100001 xor 01110011011010000 0001101100001001 which represents #(x) = 27 · 28 + 9 = 6921. Such folding, by itself, is not hashing. Patterns in the representation of elements easily survive folding. For example, the leading 0 we have used to pad the 7-bit ASCII code to an 8-bit byte remains a zero regardless of x. If we had padded with a trailing zero, all #(x) would be even. Because #(x) often has the same representation as x, or a closely related one, we drop #() and use x slightly ambiguously to denote both the original element and its interpretation as a number. 2. Scramble x [more precisely, #(x)] to obtain h(x). Any scrambling technique is a sensible try, as long as it avoids fairly obvious pitfalls. Rules of thumb: Algorithms and Data Structures 247 A Global Text
algorithms and data structures_Page_247_Chunk4787
22. Address computation ▪ Each bit of an address h(x) should depend on all bits of the key value x. In particular, don't ignore any part of x in computing h(x). Thus h(x) = x mod 213 is suspect, as only the least significant 13 bits of x affect h(x). ▪ Make sure that arithmetic progressions such as Ch1, Ch2, Ch3, … get broken up rather than being mapped into arithmetic progressions. Thus h(x) = x mod k, where k is significantly smaller than the table size m, is suspect. ▪ Avoid any function that cannot produce a uniform distribution of addresses. Thus h(x) = x2 is suspect; if x is uniformly distributed in [0, 1], the distribution of x2 is highly skewed. A hash function must be fast and simple. All of the desiderata above are obtained by a hash function of the type: h(x) = x mod m where m is the table size and a prime number, and x is the key value interpreted as an integer. No hash function is guaranteed to avoid the worst case of hashing, namely, that all elements to be stored collide on one address (this happens here if we store only multiples of the prime m). Thus a hash function must be judged in relation to the data it is being asked to store, and usually this is possible only after one has begun using it. Hashing provides a perfect example for the injunction that the programmer must think about the data, analyze its statistical properties, and adapt the program to the data if necessary. Performance analysis We analyze open addressing without deletions assuming that each address αi is chosen independently of all other addresses from a uniform distribution over A. This assumption is reasonable for double hashing and leads to the conclusion that the average cost for a search operation in a hash table is O(1) if we consider the load factor λ to be constant. We analyze the average number of probes executed as a function of λ in two cases: U(λ) for an unsuccessful search, and S(λ) for a successful search. Let pi denote the probability of using exactly i probes in an unsuccessful search. This event occurs if the first I – 1 probes hit occupied cells, and the i-th probe hits an empty cell: pi = λi–1 · (1 – λ). Let qi denote the probability that at least i probes are used in an unsuccessful search; this occurs if the first i – 1 inspected cells are occupied: qi = λi–1. qi can also be expressed as the sum of the probabilities that we probe exactly j cells, for j running from i to m. Thus we obtain The number of probes executed in a successful search for an element x equals the number of probes in an unsuccessful search for the same element x before it is inserted into the hash table. [Note: This holds only when elements are never relocated or deleted]. Thus the average number of probes needed to search for the i-th element inserted into the hash table is U((i – 1) / m), and S(λ) can be computed as the average of U(µ), for µ increasing in discrete steps from 0 to λ. It is a reasonable approximation to let µ vary continuously in the range from 0 to λ: 248
algorithms and data structures_Page_248_Chunk4788
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 22.5 suggests that a reasonable operating range for a hash table keeps the load factor λ between 0.25 and 0.75. If λ is much smaller, we waste space, if it is larger than 75 per cent, we get into a domain where the performance degrades rapidly. Note: If all searches are successful, a hash table performs well even if loaded up to 95 per cent—unsuccessful searching is the killer! Table 22.1: The average number of probes per search grows rapidly as the load factor approaches 1. λ 0.25 0.5 0.75 0.9 0.95 0.99 U(λ) 1.3 2.0 4.0 10.0 20.0 100.0 S(λ) 1.2 1.4 1.8 2.6 3.2 4.7 Exhibit 22.5: The average number of probes per search grows rapidly as the load factor approaches 1. Thus the hash table designer should be able to estimate n within a factor of 2—not an easy task. An incorrect guess may waste memory or cause poor performance, even table overflow followed by a crash. If the programmer becomes aware that the load factor lies outside this range, she may rehash—change the size of the table, change the hash function, and reinsert all elements previously stored. Extendible hashing In contrast to standard hashing methods, extendible forms of hashing allow for the dynamic extension or shrinkage of the address range into which the hash function maps the keys. This has two major advantages: (1) Memory is allocated only as needed (it is unnecessary to determine the size of the address range a priori), and (2) deletion of elements does not degrade performance. As the address range changes, the hash function is changed in such a way that only a few elements are assigned a new address and need to be stored in a new bucket. The idea that makes this possible is to map the keys into a very large address space, of which only a portion is active at any given time. Various extendible hashing methods differ in the way they represent and manage a smaller active address range of variable size that is a subrange of a larger virtual address range. In the following we describe the method of extendible hashing that is especially well suited for storing data on secondary storage devices; in this case an address points to a physical block of secondary storage that can contain more than one element. An address is a bit string of maximum length k; however, at any time only a prefix of d bits is used. If all bit strings of length k are represented by a so-called radix tree of height k, the active part of all bit strings is obtained by using only the upper d levels of the tree (i.e. by cutting the tree at level d). Exhibit 22.6 shows an example for d = 3. Algorithms and Data Structures 249 A Global Text
algorithms and data structures_Page_249_Chunk4789
22. Address computation Exhibit 22.6: Address space organized as a binary radix tree. The radix tree shown in Exhibit 22.6 (without the nodes that have been clipped) describes an active address range with addresses {00, 010, 011, 1} that are considered as bit strings or binary numbers. To each active node with address s there corresponds a bucket B that can store b records. If a new element has to be inserted into a full bucket B, then B is split: Instead of B we find two twin buckets B0 and B1 which have a one bit longer address than B, and the elements stored in B are distributed among B0 and B1 according to this bit. The new radix tree now has to point to the two data buckets B0 and B1 instead of B; that is, the active address range must be extended locally (by moving the broken line in Exhibit 22.6). If the block with address 00 overflows, two new twin blocks with addresses 000 and 001 will be created which are represented by the corresponding nodes in the tree. If the overflowing bucket B has depth d, then d is incremented by 1 and the radix tree grows by one level. In extendible hashing the clipped radix tree is represented by a directory that is implemented by an array. Let d be the maximum number of bits that are used in one of the bit strings for forming an address; in the example above, d = 3. Then the directory consists of 2d entries. Each entry in this directory corresponds to an address and points to a physical data bucket which contains all elements that have been assigned this address by the hash function h. The directory for the radix tree in Exhibit 22.6 looks as shown in Exhibit 22.7. Exhibit 22.7: The active address range of the tree in Exhibit 22.6 implemented as an array. The bucket with address 010 corresponds to a node on level 3 of the radix tree, and there is only one entry in the directory corresponding to this bucket. If this bucket overflows, the directory and data buckets are reorganized as shown in Exhibit 22.8. Two twin buckets that jointly contain fewer than b elements are merged into a single bucket. This keeps the average bucket occupancy at a high 70 per cent even in the presence of deletions, as probabilistic analysis predicts and simulation results confirm. Bucket merging may lead to halving the directory. A formerly large file that shrinks to a much smaller size will have its directory shrink in proportion. Thus extendible hashing, unlike conventional hashing, suffers no permanent performance degradation under deletions. 250
algorithms and data structures_Page_250_Chunk4790
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 22.8: An overflowing bucket may trigger doubling of the directory. A virtual radix tree: order-preserving extendible hashing Hashing, in the usual sense of the word, destroys structure and thus buys uniformity at the cost of order. Extendible hashing, on the other hand, is practical without randomization and thus needs not accept its inevitable consequence, the destruction of order. A uniform distribution of elements is not nearly as important: Nonuniformity causes the directory to be deeper and thus larger than it would be for a uniform distribution, but it affects neither access time nor bucket occupancy. And the directory is only a small space overhead on top of the space required to store the data: It typically contains only one or a few pointers, say a dozen bytes, per data bucket of, say 1k bytes; it adds perhaps a few percent to the total space requirement of the table, so its growth is not critical. Thus extendible hashing remains feasible when the identity is used as the address computation function h, in which case data is accessible and can be processed sequentially in the order ≤ defined on the domain X. When h preserves order, the word hashing seems out of place. If the directory resides in central memory and the data buckets on disk, what we are implementing is a virtual memory organized in the form of a radix tree of unbounded size. In contrast to conventional virtual memory, whose address space grows only at one end, this address space can grow anywhere: It is a virtual radix tree. As an example, consider the domain X of character strings up to length 32, say, and assume that elements to be stored are sampled according to the distribution of the first letter in English words. We obtain an approximate distribution by counting pages in a dictionary (Exhibit 22.9). Encode the blank as 00000, 'a' as 00001, up to 'z' as 11011, so that 'aah', for example, has the code 00001 00001 01000 00000 … (29 quintuples of zeros pad 'aah' to32letters). This address computation function h is almost an identity: It maps {' ', 'a', … , 'z'} 32 one-to-one into {0, 1}160. Such an order-preserving address computation function supports many useful types of operations: for example, range queries such as "list in alphabetic order all the words stored from 'unix' to 'xinu' ". Algorithms and Data Structures 251 A Global Text
algorithms and data structures_Page_251_Chunk4791
22. Address computation Exhibit 22.9: Relative frequency of words beginning with a given letter in Webster's dictionary. If there is one page of words starting with X for 160 pages of words starting with S, this suggests that if our active address space is partitioned into equally sized intervals, some intervals may be populated 160 times more densely than others. This translates into a directory that may be 160 times larger than necessary for a uniform distribution, or, since directories grow as powers of 2, may be 128 or 256 times larger. This sounds like a lot but may well be bearable, as the following estimates show. Assume that we store 105 records on disk, with an average occupancy of 100 records per bucket, requiring about 1000 buckets. A uniform distribution generates a directory with one entry per bucket, for a total of 1k entries, say 2k or 4k bytes. The nonuniform distribution above requires the same number of buckets, about 1,000, but generates a directory of 256k entries. If a pointer requires 2 to 4 bytes, this amounts to 0.5 to 1 Mbyte. This is less of a memory requirement than many applications require on today's personal computers. If the application warrants it (e.g. for an on-line reservation system) 1 Mbyte of memory is a small price to pay. Thus we see that for large data sets, extendible hashing approximates the ideal characteristics of the special case we discussed in this chapter's section on “the special case of small key domains”. All it takes is a disk and a central memory of a size that is standard today but was practically infeasible a decade ago, impossible two decades ago, and unthought of three decades ago. Exercises and programming projects 1. Design a perfect hash table for the elements 1, 10, 14, 20, 25, and 26. 2. The six names AL, FL, GA, NC, SC and VA must be distinguished from all other ordered pairs of uppercase letters. To solve this problem, these names are stored in the array T such that they can easily be found by means of a hash function h. type addr = 0 .. 7; pair = record c1, c2: 'A' .. 'Z' end; var T: array [addr] of pair; (a) Write a function h (name: pair): adr; which maps the six names onto different addresses in the range 'adr'. 252
algorithms and data structures_Page_252_Chunk4792
This book is licensed under a Creative Commons Attribution 3.0 License (b) Write a procedure initTable; which initializes the entries of the hash table T. (c) Write a function member (name: pair): boolean; which returns for any pair of uppercase letters whether it is stored in T. 3. Consider the hash function h(x) = x mod 9 for a table having nine entries. Collisions in this hash table are resolved by coalesced chaining. Demonstrate the insertion of the elements 14, 19, 10, 6, 11, 42, 21, 8, and 1. 4. Consider inserting the keys 14, 1, 19, 10, 6, 11, 42, 21, 8, and 17 into a hash table of length m = 13 using open addressing with the hash function h(x) = x mod m. Show the result of inserting these elements using (a) Linear probing. (b) Double hashing with the second hash function g(x) = 1 + x mod (m+1). 5. Implement a dictionary supporting the operations 'insert', 'delete', and 'member' as a hash table with double hashing. 6. Implement a dictionary supporting the operations 'insert', 'delete', 'member', 'succ', and 'pred' by order- preserving extendible hashing. Algorithms and Data Structures 253 A Global Text
algorithms and data structures_Page_253_Chunk4793
This book is licensed under a Creative Commons Attribution 3.0 License 23. Metric data structures Learning objectives: • organizing the embedding space versus organizing its contents • quadtrees and octtrees. grid file. two-disk-access principle • simple geometric objects and their parameter spaces • region queries of arbitrary shape • approximation of complex objects by enclosing them in simple containers Organizing the embedding space versus organizing its contents Most of the data structures discussed so far organize the set of elements to be stored depending primarily, or even exclusively, on the relative values of these elements to each other and perhaps on their order of insertion into the data structure. Often, the only assumption made about these elements is that they are drawn from an ordered domain, and thus these structures support only comparative search techniques: the search argument is compared against stored elements. The shape of data structures based on comparative search varies dynamically with the set of elements currently stored; it does not depend on the static domain from which these elements are samples. These techniques organize the particular contents to be stored rather than the embedding space. The data structures discussed in this chapter mirror and organize the domain from which the elements are drawn—much of their structure is determined before the first element is ever inserted. This is typically done on the basis of fixed points of reference which are independent of the current contents, as inch marks on a measuring scale are independent of what is being measured. For this reason we call data structures that organize the embedding space metric data structures. They are of increasing importance, in particular for spatial data, such as needed in computer-aided design or geographic data processing. Typically, these domains exhibit a much richer structure than a mere order: In two- or three-dimensional Euclidean space, for example, not only is order defined along any line (not just the coordinate axes), but also distance between any two points. Most queries about spatial data involve the absolute position of elements in space, not just their relative position among each other. A typical query in graphics, for example, asks for the first object intercepted by a given ray of light. Computing the answer involves absolute position (the location of the ray) and relative order (nearest along the ray). A data structure that supports direct access to objects according to their position in space can clearly be more efficient than one based merely on the relative position of elements. The terms "organizing the embedding space" and "organizing its contents" suggest two extremes along a spectrum of possibilities. As we have seen in previous chapters, however, many data structures are hybrids that combine features from distinct types. This is particularly true of metric data structures: They always have aspects of address computation needed to locate elements in space, and they often use list processing techniques for efficient memory utilization. Algorithms and Data Structures 254 A Global Text
algorithms and data structures_Page_254_Chunk4794
23. Metric data structures Radix trees, tries We have encountered binary radix trees, and a possible implementation, in chapter 22 in the section “Extendible hashing”. Radix trees with a branching factor, or fan-out, greater than 2 are ubiquitous. The Dewey decimal classification used in libraries is a radix tree with a fan-out of 10. The hierarchical structure of many textbooks, including this one, can be seen as a radix tree with a fan-out determined by how many subsections at depth d + 1 are packed into a section at depth d. As another example, consider tries, a type of radix tree that permits the retrieval of variable-length data. As we traverse the tree, we check whether or not the node we are visiting has any successors. Thus the trie can be very long along certain paths. As an example, consider a trie containing words in the English language. In Exhibit 23.1 below, the four words 'a', 'at', 'ate', and 'be' are shown explicitly. The letter 'a' is a word and is the first letter of other words. The field corresponding to 'a' contains the value 1, signaling that we have spelled a valid word, and there is a pointer to longer words beginning with 'a'. The letter 'b' is not a word, thus is marked by a 0, but it is the beginning of many words, all found by following its pointer. The string 'aa' is neither a word nor the beginning of a word, so its field contains 0 and its pointer is 'nil'. Exhibit 23.1: A radix tree over the alphabet of letters stores (prefixes of) words. Only a few words begin with 'ate', but among these there are some long ones, such as 'atelectasis'. It would be wasteful to introduce eight additional nodes, one for each of the characters in 'lectasis', just to record this word, without making significant use of the fan-out of 26 provided at each node. Thus tries typically use an "overflow technique" to handle long entries: The pointer field of the prefix 'ate' might point to a text field that contains '(ate-)lectasis' and '(ate-)lier'. Quadtrees and octtrees Consider a square recursively partitioned into quadrants. Exhibit 23.2 23.2 shows such a square partitioned to the depth of 4. There are 4 quadrants at depth 1, separated by the thickest lines; 4 · 4 (sub-)quadrants separated by slightly thinner lines; 43 (sub-sub-)quadrants separated by yet thinner lines; and finally, 44 = 256 leaf quadrants separated by the thinnest lines. The partitioning structure described is a quadtree, a particular type of radix tree of fan-out 4. The root corresponds to the entire square, its 4 children to the 4 quadrants at depth 1, and so on, as shown in the Exhibit 23.2. 255
algorithms and data structures_Page_255_Chunk4795
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 23.2: A quarter circle digitized on a 16 · 16 grid, and its representation as a 4-level quadtree. A quadtree is the obvious two-dimensional analog of the one-dimensional binary radix tree we have seen. Accordingly, quadtrees are frequently used to represent, store, and process spatial data, such as images. The figure shows a quarter circle, digitized on a 16 · 16 grid of pixels. This image is most easily represented by a 16 · 16 array of bits. The quadtree provides an alternative representation that is advantageous for images digitized to a high level of resolution. Most graphic images in practice are digitized on rectangular grids of anywhere from hundreds to thousands of pixels on a side: for example, 512 · 512. In a quadtree, only the largest quadrants of constant color (black or white, in our example) are represented explicitly; their subquadrants are implicit. The quadtree in Exhibit 23.2 is interpreted as follows. Of the four children of the root, the northwest quadrant, labeled 1, is simple: entirely white. This fact is recorded in the root. The other three children, labeled 0, 2, and 3, contain both black and white pixels. As their description is not simple, it is contained in three quadtrees, one for each quadrant. Pointers to these subquadtrees emanate from the corresponding fields of the root. The southwestern quadrant labeled 2 in turn has four quadrants at depth 2. Three of these, labeled 2.0, 2.1, and 2.2, are entirely white; no pointers emanate from the corresponding fields in this node. Subquadrant 2.3 contains both black and white pixels; thus the corresponding field contains a pointer to a sub-subquadtree. In this discussion we have introduced a notation to identify every quadrant at any depth of the quadtree. The root is identified by the null string; a quadrant at depth d is uniquely identified by a string of d radix-4 digits. This string can be interpreted in various ways as a number expressed in base 4. Thus accessing and processing a quadtree is readily reduced to arithmetic. Breadth-first addressing Label the root 0, its children 1, 2, 3, 4, its grand children 5 through 20, and so on, one generation after the other. Algorithms and Data Structures 256 A Global Text
algorithms and data structures_Page_256_Chunk4796
23. Metric data structures 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Notice that the children of any node i are 4 · i + 1, 4 · i + 2, 4 · i + 3, 4 · i + 4. The parent of node i is (i – 1) div 4. This is similar to the address computation used in the heap of “Implicit data structures”, a binary tree where each node i has children 2 · i and 2 · i + 1; and the parent of node i is obtained as i div 2. Exercise The string of radix 4 digits along a path from the root to any node is called the path address of this node. Interpret the path address as an integer, most significant digit first. These integers label the nodes at depth d > 0 consecutively from 0 to 4d – 1. Devise a formula that transforms the path address into the breadth-first address. This formula can be used to store a quadtree as a one-dimensional array. Data compression The representation of an image as a quadtree is sometimes much more compact than its representation as a bit map. Two conditions must hold for this to be true: 1. The image must be fairly large, typically hundreds of pixels on a side. 2. The image must have large areas of constant value (color). The quadtree for the quarter circle above, for example, has only 14 nodes. A bit map of the same image requires 256 bits. Which representation requires more storage? Certainly the quadtree. If we store it as a list, each node must be able to hold four pointers, say 4 or 8 bytes. If a pointer has value 'nil', indicating that its quadrant needs no refinement, we need a bit to indicate the color of this quadrant (white or black), or a total of 4 bits. If we store the quadtree breadth-first, no pointers are needed as the node relationships are expressed by address computation; thus a node is reduced to four three-valued fields ('white', 'black', or 'refine'), conveniently stored in 8 bits, or 1 byte. This implicit data structure will leave many unused holes in memory. Thus quadtrees do not achieve data compression for small images. Octtrees Exactly the same idea for three-dimensional space as quadtrees are for two-dimensional space: A cube is recursively partitioned into eight octants, using three orthogonal planes. Spatial data structures: objectives and constraints Metric data structures are used primarily for storing spatial data, such as points and simple geometric objects embedded in a multidimensional space. The most important objectives a spatial data structure must meet include: 1. Efficient handling of large, dynamically varying data sets in interactive applications 2. Fast access to objects identified in a fully specified query 3. Efficient processing of proximity queries and region queries of arbitrary shape 4. A uniformly high memory utilization Achieving these objectives is subject to many constraints, and results in trade-offs. Managing disks. By "large data set" we mean one that must be stored on disk; only a small fraction of the data can be kept in central memory at any one time. Many data structures can be used in central memory, but the choice is much more restricted when it comes to managing disks because of the well-known "memory speed gap" 257
algorithms and data structures_Page_257_Chunk4797
This book is licensed under a Creative Commons Attribution 3.0 License phenomenon. Central memory is organized in small physical units (a byte, a word) with access times of approximately 1 microsecond, 10–6 second. Disks are organizein large physical blocks (512 bytes to 5kilobytes) with access times ranging from 10 to 100 milliseconds (10–2 to 10–1 second). Compared to central memory, a disk delivers data blocks typically 103 times larger with a delay 104 times greater. In terms of the data rate delivered to the central processing unit: the disk is a storage device whose effectiveness is within an order of magnitude of that of central memory. The large size of a physical disk block is a potential source of inefficiency that can easily reduce the useful data rate of a disk a hundredfold or a thousandfold. Accessing a couple of bytes on disk, say a pointer needed to traverse a list, takes about as long as accessing the entire disk block. Thus the game of managing disks is about minimizing the number of disk accesses. Dynamically varying data. The majority of computer applications today are interactive. That means that insertions, deletions, and modifications of data are at least as frequent as operations that merely process fixed data. Data structures that entail a systematic degradation of performance with continued use (such as ever-lengthening overflow chains, or an ever-increasing number of cells marked "deleted" in a conventional hash table) are unsuitable. Only structures that automatically adapt their shape to accommodate ever-changing contents can provide uniform response times. Instantaneous response. Interactive use of computers sets another major challenge for data management: the goal of providing "instantaneous response" to a fully specified query. "Fully" specified means that every attribute relevant for the search has been provided, and that at most one element satisfies the query. Imagine the user clicking an icon on the screen, and the object represented by the icon appears instantaneously. In human terms, "instantaneous" is a well-defined physiological quantity, namely, about of a second, the limit of human time resolution. Ideally, an interactive system retrieves any single element fully specified in a query within 0.1 second. Two-disk-access principle. We have already stated that in today's technology, a disk access typically takes from tens of milliseconds. Thus the goal of retrieving any single element in 0.1 second translates into "retrieve any element in at most a few disk accesses". Fortunately, it turns out that useful data structure can be designed that access data in a two-step process: (1) access the correct portion of a directory, and (2) access the correct data bucket. Under the assumption that both data and directory are so large that they are stored on disk, we call this the two-disk-access principle. Proximity queries and region queries of arbitrary shape. The simplest example of a proximity query is the operation 'next', which we have often encountered in one-dimensional data structure traversals: Given a pointer to an element, get the next element (the successor or the predecessor) according to the order defined on the domain. Another simple example is an interval or range query such as "get all x between 13 and 17". This generalizes directly to k-dimensional orthogonal range queries such as the two-dimensional query "get all (x1, x2) with 13 ≤ x1 < 17 and 3 ≤ x2 < 4". In geometric computation, for example, many other instances of proximity queries are important, such as the "nearest neighbor" (in any direction), or intersection queriesamong objects. Region queries of arbitrary shape (not just rectangular) are able to express a variety of geometric conditions. Algorithms and Data Structures 258 A Global Text
algorithms and data structures_Page_258_Chunk4798
23. Metric data structures Uniformly high memory utilization. Any data structure that adapts its shape to dynamically changing contents is likely to leave "unused holes" in storage space: space that is currently unused, and that cannot conveniently be used for other purposes because it is fragmented. We have encountered this phenomenon in multiway trees such as B-trees and in hash tables. It is practically unavoidable that dynamic data structures use their allocated space to less than 100%, and an average space utilization of 50% is often tolerable. The danger to avoid is a built-in bias that drives space utilization toward 0 when the file shrinks—elements get deleted but their space is not relinquished. The grid file, to be discussed next, achieves an average memory utilization of about 70% regardless of the mix of insertions or deletions. The grid file The grid file is a metric data structure designed to store points and simple geometric objects in multidimensional space so as to achieve the objectives stated above. This section describes its architecture, access and update algorithms, and properties. More details can be found in [NHS 84] and [Hin 85]. Scales, directory, buckets Consider as an example a two-dimensional domain: the Cartesian product X1 × X2, where X1 = 0 .. 1999 is a subrange of the integers, and X2 = a .. z is the ordered set of the 26 characters of the English alphabet. Pairs of the form (x1, x2), such as (1988, w), are elements from this domain. The bit map is a natural data structure for storing a set S of elements from X1 × X2. It may be declared as var T: array[X1, X2] of boolean; with the convention that T[x1, x2] = true ⇔ (x1, x2) ∈ S. Basic set operations are performed by direct access to the array element corresponding to an element: find(x 1, x2) is simply the boolean expression T[x1, x2]; insert(x1, x2) is equivalent to T[x1, x2]:= 'true', delete(x1, x2) is equivalent to T[x1, x2] := 'false'. The bit map for our small domain requires an affordable 52k bits. Bit maps for realistic examples are rarely affordable, as the following reasoning shows. First, consider that x and y are just keys of records that hold additional data. If space is reserved in the array for this additional data, an array element is not a bit but as many bytes as are needed, and all the absent records, for elements (x1, x2) ∉ S, waste a lot of storage. Second, most domains are much larger than the example above: the three-dimensional Euclidean space, for example, with elements (x, y, z) taken as triples of 32-bit integers, or 64-bit floating-point numbers, requires bit maps of about 1030 and 1060 bits, respectively. For comparison's sake: a large disk has about 1010 bits. Since large bit maps are extremely sparsely populated, they are amenable to data compression. The grid file is best understood as a practical data compression technique that stores huge, sparsely populated bit maps so as to support direct access. Returning to our example, imagine a historical database indexed by the year of birth and the first letter of the name of scientists: thus we find 'John von Neumann' under (1903, v). Our database is pictured as a cloud of points in the domain shown in Exhibit 23.3; because we have more scientists (or at least, more records) in recent years, the density increases toward the right. Storing this database implies packing the records into buckets of fixed capacity to hold c (e.g. c = 3) records. The figure shows the domain partitioned by orthogonal hyperplanes into box-shaped grid cells, none of which contains more than c points. 259
algorithms and data structures_Page_259_Chunk4799
This book is licensed under a Creative Commons Attribution 3.0 License Exhibit 23.3: Cells of a grid partition adapt their size so that no cell is populated by more than c points. A grid file for this database contains the following components: • Linear scales show how the domain is currently partitioned. • The directory is an array whose elements are in one-to-one correspondence with the grid cells; each entry points to a data bucket that holds all the records of the corresponding grid cell. Access to the record (1903, v) proceeds through three steps: 1. Scales transform key values to array indices: (1903, v) becomes (5, 4). Scales contain small amounts of data, which is kept in central memory; thus this step requires no disk access. 2. The index tuple (5, 4) provides direct access to the correct element of the directory. The directory may be large and occupy many pages on disk, but we can compute the address of the correct directory page and in one disk access retrieve the correct directory element. 3. The directory element contains a pointer (disk address) of the correct data bucket for (1903, v), and the second disk access retrieves the correct record: [(1903, v), John von Neumann …]. Disk utilization The grid file does not allocate a separate bucket to each grid cell—that would lead to an unacceptably low disk utilization. Exhibit 23.4 suggests, for example, that the two grid cells at the top right of the directory share the same bucket. How this bucket sharing comes about, and how it is maintained through splitting of overflowing buckets, and merging sparsely populated buckets, is shown in the following. Algorithms and Data Structures 260 A Global Text
algorithms and data structures_Page_260_Chunk4800