Data Structures and Algorithms in Java 4th phần 5 ppsx

92 731 0
Data Structures and Algorithms in Java 4th phần 5 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

methods of the array list ADT on such a representation. Is it better to store the entries in L by increasing indices or not? C-6.17 There is a simple, but inefficient, algorithm, called bubble-sort, for sorting a sequence S of n comparable elements. This algorithm scans the sequence n−1 times, where, in each scan, the algorithm compares the current element with the next one and swaps them if they are out of order. Give a pseudo-code description of bubble-sort that is as efficient as possible assuming S is implemented with a doubly linked list. What is the running time of this algorithm? C-6.18 Answer Exercise C-6.17 assuming S is implemented with an array list. C-6.19 A useful operation in databases is the natural join. If we view a database as a list of ordered pairs of objects, then the natural join of databases A and B is the list of all ordered triples (x,y,z) such that the pair (x,y) is in A and the pair (y,z) is in B. Describe and analyze an efficient algorithm for computing the natural join of a list A of n pairs and a list B of m pairs. C-6.20 When Bob wants to send Alice a message M on the Internet, he breaks M into n data packets, numbers the packets consecutively, and injects them into the network. When the packets arrive at Alice's computer, they may be out of order, so Alice must assemble the sequence of n packets in order before she can be sure she has the entire message. Describe an efficient scheme for Alice to do this. What is the running time of this algorithm? C-6.21 Given a list L of n positive integers, each represented with k = logn + 1 bits, describe an O(n)-time method for finding a k-bit integer not in L. C-6.22 Argue why any solution to the previous problem must run in Ω(n) time. C-6.23 Given a list L of n arbitrary integers, design an O(n)-time method for finding an integer that cannot be formed as the sum of two integers in L. 370 C-6.24 Isabel has an interesting way of summing up the values in an array A of n integers, where n is a power of two. She creates an array B of half the size of A and sets B[i] = A[2i] +A[2i+ 1], for i = 0,1, , (n/2) − 1. If B has size 1, then she outputs B[0]. Otherwise, she replaces A with B, and repeats the process. What is the running time of her algorithm? Projects P-6.1 Implement the array list ADT by means of an extendable array used in a circular fashion, so that insertions and deletions at the beginning and end of the array list run in constant time. P-6.2 Implement the array list ADT using a doubly linked list. Show experimentally that this implementation is worse than the array-based approach. P-6.3 Write a simple text editor, which stores and displays a string of characters using the list ADT, together with a cursor object that highlights a position in this string. Your editor should support the following operations: • left: Move cursor left one character (do nothing if at text end). • right: Move cursor right one character (do nothing if at text end). • cut: Delete the character right of the cursor (do nothing at text end). • paste c: Insert the character c just after the cursor. P-6.4 Implement a phased favorites list. A phase consists of N accesses in the list, for a given parameter N. During a phase, the list should maintain itself so that elements are ordered by decreasing access counts during that phase. At the end 371 of a phase, it should clear all the access counts and start the next phase. Experimentally, determine what are the best values of N for various list sizes. P-6.5 Write a complete adapter class that implements the sequence ADT using a java.util.ArrayList object. P-6.6 Implement the favorites list application using an array list instead of a list. Compare it experimentally to the list-based implementation. Chapter Notes The concept of viewing data structures as collections (and other principles of object- oriented design) can be found in object-oriented design books by Booch [14], Budd [17], Golberg and Robson [40], and Liskov and Guttag [69]. Lists and iterators are pervasive concepts in the Java Collections Framework. Our node list ADT is derived from the "position" abstraction introduced by Aho, Hopcroft, and Ullman [5], and the list ADT of Wood [100]. Implementations of lists via arrays and linked lists are discussed by Knuth [62]. 372 Chapter 7 Trees Contents 7.1 General Trees 266 7.1.1 Tree Definitions and Properties 267 7.1.2 The Tree Abstract Data Type 373 270 7.1.3 Implementing a Tree 271 7.2 Tree Traversal Algorithms 273 7.2.1 Depth and Height 273 7.2.2 Preorder Traversal 276 7.2.3 Postorder Traversal 279 7.3 Binary Trees 282 7.3.1 The Binary Tree ADT 284 7.3.2 A Binary Tree Interface in Java 284 374 7.3.3 Properties of Binary Trees 285 7.3.4 A Linked Structure for Binary Trees 287 7.3.5 An Array-List Representation of a Binary Tree 296 7.3.6 Traversals of Binary Trees 298 7.3.7 The Template Method Pattern 305 7.4 Exercises 309 java.datastructures.net 7.1 General Trees Productivity experts say that breakthroughs come by thinking "nonlinearly." In this chapter, we discuss one of the most important nonlinear data structures in computing—trees. Tree structures are indeed a breakthrough in data organization, for they allow us to implement a host of algorithms much faster than when using linear data structures, such as list. Trees also provide a natural organization for data, and consequently have become ubiquitous structures in file systems, graphical user interfaces, databases, Web sites, and other computer systems. 375 It is not always clear what productivity experts mean by "nonlinear" thinking, but when we say that trees are "nonlinear," we are referring to an organizational relationship that is richer than the simple "before" and "after" relationships between objects in sequences. The relationships in a tree are hierarchical, with some objects being "above" and some "below" others. Actually, the main terminology for tree data structures comes from family trees, with the terms "parent," "child," "ancestor," and "descendent" being the most common words used to describe relationships. We show an example of a family tree in Figure 7.1. Figure 7.1: A family tree showing some descendents of Abraham, as recorded in Genesis, chapters 25–36. 7.1.1 Tree Definitions and Properties A tree is an abstract data type that stores elements hierarchically. With the exception of the top element, each element in a tree has a parent element and zero or more children elements. A tree is usually visualized by placing elements inside ovals or rectangles, and by drawing the connections between parents and children with straight lines. (See Figure 7.2.) We typically call the top element the root of the tree, but it is drawn as the highest element, with the other elements being connected below (just the opposite of a botanical tree). Figure 7.2: A tree with 17 nodes representing the organization of a fictitious corporation. The root stores 376 Electronics R'Us. The children of the root store R&D, Sales, Purchasing, and Manufacturing. The internal nodes store Sales, International, Overseas, Electronics R'Us, and Manufacturing. Formal Tree Definition Formally, we define a tree T as a set of nodes storing elements such that the nodes have a parent-child relationship, that satisfies the following properties: • If T is nonempty, it has a special node, called the root of T, that has no parent. • Each node v of T different from the root has a unique parent node w; every node with parent w is a child of w. Note that according to our definition, a tree can be empty, meaning that it doesn't have any nodes. This convention also allows us to define a tree recursively, such that a tree T is either empty or consists of a node r, called the root of T, and a (possibly empty) set of trees whose roots are the children of r. Other Node Relationships 377 Two nodes that are children of the same parent are siblings. A node v is external if v has no children. A node v is internal if it has one or more children. External nodes are also known as leaves. Example 7.1: In most operating systems, files are organized hierarchically into nested directories (also called folders), which are presented to the user in the form of a tree. (See Figure 7.3.) More specifically, the internal nodes of the tree are associated with directories and the external nodes are associated with regular files. In the UNIX and Linux operating systems, the root of the tree is appropriately called the "root directory," and is represented by the symbol "/." Figure 7.3: Tree representing a portion of a file system. A node u is an ancestor of a node v if u = v or u is an ancestor of the parent of v. Conversely, we say that a node v is a descendent of a node u if u is an ancestor of v. For example, in Figure 7.3 , cs252/ is an ancestor of papers/, and pr3 is a descendent of cs016/. The subtree of T rooted at a node v is the tree consisting of all the descendents of v in T (including v itself). In Figure 7.3 , the subtree rooted at cs016/ consists of the nodes cs016/, grades, homeworks/, programs/, hw1, hw2, hw3, pr1, pr2, and pr3. 378 Edges and Paths in Trees An edge of tree T is a pair of nodes (u, v) such that u is the parent of v, or vice versa. A path of T is a sequence of nodes such that any two consecutive nodes in the sequence form an edge. For example, the tree in Figure 7.3 contains the path (cs252/, projects/, demos/, market). Example 7.2: The inheritance relation between classes in a Java program forms a tree. The root, java. lang. Object, is an ancestor of all other classes. Each class, C, is a descendent of this root and is the root of a subtree of the classes that extend C. Thus, there is a path from C to the root, java.lang.Object, in this inheritance tree. Ordered Trees A tree is ordered if there is a linear ordering defined for the children of each node; that is, we can identify the children of a node as being the first, second, third, and so on. Such an ordering is usually visualized by arranging siblings left to right, according to their ordering. Ordered trees typically indicate the linear order among siblings by listing them in the correct order. Example 7.3: The components of a structured document, such as a book, are hierarchically organized as a tree whose internal nodes are parts, chapters, and sections, and whose external nodes are paragraphs, tables, figures, and so on. (See Figure 7.4.) The root of the tree corresponds to the book itself. We could, in fact, consider expanding the tree further to show paragraphs consisting of sentences, sentences consisting of words, and words consisting of characters. Such a tree is an example of an ordered tree, because there is a well-defined ordering among the children of each node. Figure 7.4: An ordered tree associated with a book. 379 [...]... tree in internal variables In 404 addition to the Binary Tree interface methods, LinkedBinaryTree has various other methods, including accessor method sibling(v), which returns the sibling of a node v, and the following update methods: addRoot(e): Create and return a new node r storing element e and make r the root of the tree; an error occurs if the tree is not empty insertLeft(v,e): Create and return... of a binary tree in Figure 7.14b Figure 7.14: A node (a) and a linked structure (b) for representing a binary tree 401 Java Implementation of a Binary Tree Node 402 We use a Java interface BTPosition (not shown) to represent a node of a binary tree This interfaces extends Position, thus inheriting method element, and has additional methods for setting the element stored at the node (setElement) and for... Nodes in a Proper Binary Tree In addition to the binary tree properties above, we also have the following relationship between the number of internal nodes and external nodes in a proper binary tree Proposition 7.11: In a nonempty proper binary tree T, with n E external nodes and n I internal nodes, we have n e = n I + 1 Justification: We justify this proposition by removing nodes from T and dividing... Fragment 7.14, we show the simple Java interface we can define using this approach By the way, since binary trees are ordered trees, the iterable collection returned by method children(v) (inherited from the Tree interface) stores the left child of v before the right child of v Code Fragment 7.14: Java interface Binary Tree for the binary tree ADT Interface Binary Tree extends interface Tree (Code Fragment... parent of v, respectively Code Fragment 7. 15: Auxiliary class BTNode for implementing binary tree nodes 403 Java Implementation of the Linked Binary Tree Structure In Code Fragments 7.16–7.18, we show portions of class Linked Binary Tree that implements the Binary Tree interface (Code Fragment 7.14) using a linked data structure This class stores the size of the tree and a reference to the BTNode object... in Section 7.1.2 for the tree ADT, we do not define specialized update methods for binary trees here Instead, we will consider some possible update methods when we describe specific implementations and applications of binary trees 7.3.2 A Binary Tree Interface in Java We model a binary tree as an abstract data type that extends the tree ADT and adds the three specialized methods for a binary tree In. .. w and its parent v, which is an internal node We place w on the external-node pile and v on the internal-node pile If v has a parent u, then we reconnect u with the former sibling z of w, as shown in Figure 7.13 This operation, removes one internal node and one external node, and leaves the tree being a proper binary tree Repeating this operation, we eventually are left with a final tree consisting... Definition Incidentally, we can also define a binary tree in a recursive way such that a binary tree is either empty or consists of: • A node r, called the root of T and storing an element • A binary tree, called the left subtree of T • A binary tree, called the right subtree of T We discuss some of the specialized topics for binary trees below 7.3.1 The Binary Tree ADT As an abstract data type, a binary... Attach T 1 and T 2 , respectively, as the left and right subtrees of the external node v; an error condition occurs if v is not external Class LinkedBinaryTree has a constructor with no arguments that returns an empty binary tree Starting from this empty tree, we can build any binary tree by creating the first node with method addRoot and repeatedly applying the insertLeft and insertRight methods and/ or... parent node, used in the justification of Proposition 7.11 Note that the above relationship does not hold, in general, for improper binary trees and nonbinary trees, although there are other interesting relationships that can hold, as we explore in an exercise (C-7.7) 7.3.4 Trees A Linked Structure for Binary As with a general tree, a natural way to realize a binary tree T is to use a linked structure, . come by thinking "nonlinearly." In this chapter, we discuss one of the most important nonlinear data structures in computing—trees. Tree structures are indeed a breakthrough in data organization,. 279 7.3 Binary Trees 282 7.3.1 The Binary Tree ADT 284 7.3.2 A Binary Tree Interface in Java 284 374 7.3.3 Properties of Binary Trees 2 85 7.3.4 A Linked Structure for Binary Trees. arbitrary integers, design an O(n)-time method for finding an integer that cannot be formed as the sum of two integers in L. 370 C-6.24 Isabel has an interesting way of summing up the values in

Ngày đăng: 14/08/2014, 01:21

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan