Free Essay

Treap Data Structure

In: Computers and Technology

Submitted By meramesh
Words 1803
Pages 8
Assignment: Binary Search Tree + Heap = Treap
October 10, 2012
Binary search tree, as shown in figure 1, is a binary tree data structure which is used to hold key-value pairs and satisfies following properties; • The left subtree of any node contains only those nodes with keys less than the node’s key. • The right subtree of any node contains only those nodes with keys greater than the node’s key. key=10 val="AU"

key=8 val="BN"

key=15 val="TN"

key=12 val="NZ"

key=17 val="DL"

key=19 val="IN"

Figure 1: An example Binary Search Tree These ordering constraints help to find out a node with a given key in O(log n) average time. Insertion and deletion operations in BST (Binary search tree) must maintain these ordering constraints. prio: 8 val: "IN"

prio: 15 val: "NZ"

prio: 18 val: "AU"

prio: 25 val: "TN"

prio: 30 val: "BN"

prio: 20 val: "AP"

prio: 22 val: "RS"

Figure 2: An example min-heap Heap is an another binary tree data structure, as shown in figure 2, which is useful in sorting (heapsort) and implementing a priority queue. A heap can be a min-heap or a max-heap based on the priority of a node with respect to the 1

priority of its left and right children. In case of min-heap each node has lesser priority than its children. In case of max-heap each node has higher priority than its children. In this assignment we are going to implement a binary tree data structure which is a combination of BST and heap. This data structure is called Treap. Treap Treap is a binary tree data structure where each node contains 3 attributes; • Priority: This is used to maintain the heap status of treap. Each node in a Treap must have lower priority than its children. (in case of min-heap). • Key: This is used to maintain the BST status of treap. Every node in the left sub-tree of a node must have lesser key numbers than node’s key. Similarly every node in the right sub-tree of a node must have larger key numbers than node’s key. • Value: This represents the actual value stored in a node. prio:62 key:490 val:"IN"

prio:70 key:310 val:"AU"

prio:80 key:520 val:"BN"

prio:90 key:225 val:"SN"

prio:100 key:400 val:"TU"

prio:105 key:500 val:"TN"

prio:110 key:540 val:"PK"

Figure 3: An example treap An example treap is shown in figure 3 which satisfies the properties of BST, with respect to “key”, and the properties of min-heap, with respect to “priority”. Following operations are defined over a treap T . • search(key): Given a key k find out the value associated with this key, if any, present in T . For example, calling function search(400) on the treap of figure 3 returns “TU”. On the other hand, search(420) returns -1 denoting that there is no node in the treap matching this key. • deletion(key): Given a key k deletes that node of T whose key matches with k. Based on the type of deleted node, internal node or leaf node, treap is adjusted (changed) so as to satisfy the Treap invariants (ordering constraints over priorities and keys). • insertion(key, value, priority): Given a key k, value v and priority p this function inserts a node having these attributes at appropriate position in T . This method should make sure that the invariants of Treap are satisfied after this insertion. Note that insertion happens according to the BST property and then if any heap order violations occur, procedure similar to AVL trees is applied. 2

• changing the priority (key, newpriority): Given a key k it first searches for a node in T whose key matches with k. If such a node is found then its priority is changed to newpriority. As a result of this change the Treap invariants might get violated. Appropriate steps must be taken to establish these invariants again in T . Problem statement There are two parts of this assignment. First, you have to implement treap data structure by writing a class Treap and associated methods as below. Listing 1: An empty public java class. class Treap { int mKey ; int mValue ; int mPriority ; Treap mLeft = null ; Treap mRight = null ; // Other attributes / variables of this class as needed . public int Search ( int key ) throws K e y N o t F o u n d I n T r e a p {

} public Treap Delete ( int key ) throws K e y N o t F o u n d I n T r e a p {

} public Treap Insert ( int key , int value , int priority ) throws K e y A l r e a d y E x i s t s I n T r e a p { } public Treap ModifyPriority ( int key , int newpriority ) throws K e y N o t F o u n d I n T r e a p { }

public void DumpTreap ( String filename ){ } // Other methods of this class as needed . }

You can add more methods and attributes to this class depending upon your implementation. You will also implement exception classes KeyAlreadyExistsInTreap and KeyNotFoundInTreap which are used to denote whether or not a given key


exits in a given treap. In the second part of this assignment you will use your implementation of Treap class to give following command line user interface.

Press any number (1 -6) to denote your choice : 1. Insert a node in the treap 2. Delete a node in the treap 3. Search a node in the treap 4. Modify the priority of a node 5. Output the treap data structure to a file 6. Exit from this menu

If user enters 1 then your program will ask user for a key, a value and a priority of the new node and insert it in the treap. If user enters 2 then your program will ask user for a key and then delete the node having this key from the current treap. If user enters 3 then your program ask user for a key and returns the value associated with this key, if any, in the current treap. If user enters 4 then ask user for a key and new priority and modify the priority in the current treap. During any of these actions appropriate error messages must be shown to the user. For example searching or deleting a node that does not exists in the current treap must inform the user that no such node exists. Similarly inserting a key that is already in the current treap should inform user that a node with the same key already exists. It is your responsibility to handle all error cases which can arise because of user’s interaction with your program. One important point to note is that after your program completes the command given by the user it should not exit. After completing a given command it should again display the choices to the user. User should be able to exit your program by entering option 6 from this menu. If user enters 5 then you must ask user for an output file name and then traverse the treap data structure to write it in the given file. Following paragraph describes the format used for writing treap in a file and how to use it in your debugging activities. Note: • The input and all the interaction with the user would be through command line. • You can assume an empty tree at the beginning and user would first insert an item which would become the root of the tree. i.e tree should be built from scratch. • The attributes and methods given above should be kept according to the format mentioned. New variables or methods can be added though. Dot format for writing graphs Dot is a very popular format for writing graphs in textual form. Once a graph is described using this format then there exists many graph rendering tools which take this dot file as input and draw the graph. In this assignment we will use this dot format to dump our treap data structure in a file. Following is an example dot file which contains a very small treap structure. 4

digraph G { 0 [ color = " Black " , label = " Key :1 , Value :23 , Prio :3 " ]; 1 [ color = " Blue " , label = " Key :2 , Value :3 , Prio :5 " ]; 2 [ color = " Red " , label = " Key :5 , Value : 19 , Prio :2 " ]; 0 - >1; 0 - >2; }

Every dot file starts with digraph G. Line 2, 3 and 4 describe nodes of this graph. Each of these lines start with an integer which uniquely identifies a given node. Rest of the text (in between square brackets) define properties of this node. In our case we want to print the key, value and the priority of that node. Therefore we put all these things as label of that node. You will notice that in lines 2, 3 and 4 while defining a node we also specify its color. We will follow the convention that if a node is a left child of its parent then it must be in blue color, if it is right child of its parent then it must be in red color and the root node must be black in color. After specifying all nodes and their properties now we need to specify their connections. Last two lines (0− > 1) and (0− > 2) denotes that the node denoted by integer 0 (defined in line 2) is connected to the node denoted by integer 1 (defined in line 3). Notice that this is a directed relationship and therefore 0 is the parent of 1. Similarly in line 6, (0− > 2) denotes that node 0 is connected to node 2. Also note that 1 is the left child of 0 because color of node 1 is described as blue according to the above convention and similarly for node 2. For any node, the node property should be described before assigning it as child of any other node. Let us assume that the output file used for dumping treap in dot format is “”. Now we can use one of these very useful graphviewer tools; dotty (available for linux) or Graphviz (for windows you can download it from for visualizing the current state of treap. These tools graphically render the graph specified in dot format. Following command is used to view the tree dumped in this dot file. • dotty It is recommended that you first complete the implementation of dumpTreap function (to dump your treap in dot format) so that you can graphically visualize the outcome of your insert, delete, modifypriority operations and debug them.


Similar Documents

Premium Essay


...This general problem is known as the vehicle routing problem.Solving the vehicle routing problem involves determining how many vehicles are required to service the destinations, and developing a route and schedule for each one. Because there are many variations of the problem, it can be very dillicult to solve. TransCAD provides a rich set of vehicle routing tools that solve various types of routing problerns,These tools are used to prepare input data, solve the routing problem, and provide tabular and graphical output of the resulting routes and vehicle schedules. The starting points for each route (such as the warehouse in the above example) are known as depots, and the points to be visited are known as stops. A vehicle route starts at a depot, visits one ormore stops, and may or may not return to the depot. The goal of the procedure is to obtain a set of routes that minimizes the total time or discance traveled by the entire fleet of vehicles. The travel times or distances are stored in the vehicle routing matrix.You can use a network to calculate the network driving time or distance, or you can use straight line distances to create your vehicle routing matrix. You must use a network-based vehicle routing matrix if you want to display the routes on a map as a route system layer.Time window- There are time restrictions on when deliveries can be made to some or all of the stores Each stop requires a certain amount of time to service. The service time can have a fixed......

Words: 3610 - Pages: 15

Free Essay

Continuous Skyline Queries for Moving Objects

...Omar Khairy El -Morsy ABSTRACT The literature on the skyline algorithms so far mainly deal with queries for static query points over static datasets. With the increasing number of mobile service applications and users, the need for continuous skyline query processing has become more pressing. The continuous skyline operator involves not only static but also dynamic dimensions. In this paper, we examine the spatio-temporal coherence of the problem and propose a continuous skyline query processing strategy for moving query points. First, we distinguish the data points that are permanently in the skyline and use them to derive a search bound. Second, we investigate into the connection between data points’ spatial positions and their dominance relationship, which provides an indication on where to find changes of skyline and how to update the skyline continuously. Based on the analysis, we propose a kinetic-based data structure and an efficient skyline query processing algorithm. We analyze the space and time costs of the proposed method and conduct an extensive experiment to evaluate the proposal. To the best of our knowledge, this is the first work on continuous skyline query processing. shown in Figure 1, there are a set of hotels and for each hotel, we have its distance from the beach (x axis) and its price (y axis). The interesting hotels are all the points not worse than any other point in both distance from the beach and the price. Hotels 2, 4 and 6 are interesting and......

Words: 11922 - Pages: 48

Free Essay

Mountain View Community Hospital

...Case Study Mountain vew community hospital Case Study Mountain vew community hospital 2014 Case Study: Mountain View Community Hospital 1. Mountain View Community Hospital (MVCH) wants to provide better services than their current deliverables. Therefore, databases can help MVCH reach their goal through making relational applications provide information about clients or patients without having a book or paperwork to search for every time. A centralized database application that is not a conjunction of separate applications makes information fluid and accessible without much of a hassle. For example, when a surgeon at MVCH would want information of a patient who has visited before, the surgeon could run an application on a handheld device that collects information from the database. At the same time, when the doctor is checking the file information on the patient, the nurse or other staff member can also access the information of the patient to know what is wrong with the patient exactly. This was, the efficiency of doctors and other members of the hospital can work in collaboration flawlessly. If the database is managed well, when government inspections are taken, the hospital can provide the required information as soon as possible, keeping the hospital’s integrity to the mark with the government. 2. Database technology can take various forms when it comes to complying with security standards of patients and their information. Firstly, the database can......

Words: 850 - Pages: 4

Free Essay

Database Assigment

... Explain the differences between user views, a conceptual schema, and an internal schema as different perspectives of the same database. 5. In the three-schema architecture: a) The view of a manager or other type of user is called the schema. b) The view of the data architect or data administrator is called the schema. c) The view of the database administrator is called the schema. 6. Why might Pine Valley Furniture Company need a data warehouse? 7. As the ability to handle large amounts of data improves, describe three business areas where these very large databases are being used effectively. 8. In the section "Disadvantages of File Processing Systems," the statement is made that the disadvantages of file processing systems can also be limitations of databases, depending on how an organization manages its databases. First, why do organizations create multiple databases, not just one all-inclusive database supporting all data processing needs? Second, what organizational and personal factors are at work that might lead an organization to have...

Words: 408 - Pages: 2

Free Essay

Ibm Db2

...processors and supports up to 2GB of system memory. Insights gained from working with the database after installed are also shared. Installation Process for DB2 Express-C Downloading and installing DB2 Express-C is easily accomplished over an Internet connection. The version installed is 389MB and took approximately 10 minutes to download over a cable modem running at fractional T1 speeds. Installation screens from the steps completed to get DB2 Express-C up and running are shown in the Appendix of this document. After installing the Control Center was invoked at the command line using the command db2cc which is specifically defined in the chapter assigned on DB2 Express-C. Using the command db2sampl -xml –sql to create the sample data worked, and there is the secondary option of using graphical interface commands to accomplish the same. The use of the DB2 Command Line tools show how quickly a multidimensional table can be viewed, edited and batch programming tasks completed using shell scripts in this interface. IBM has done an excellent job of making this free version of DB2 as fully featured and full of navigational and command options as possible. What is most significant amount the design of DB2 relative to other databases worked with is the multiple approaches to getting commands invoked the flexibility on creating fully automated responses to queries, or the option of...

Words: 728 - Pages: 3

Free Essay

Parallel Querying of Rolap Cubes in the Presence of Hierarchies

...Analytical Processing is a powerful framework for the analysis of organizational data. OLAP is often supported by a logical structure known as a data cube, a multidimen- sional data model that offers an intuitive array-based per- spective of the underlying data. Supporting efficient index- ing facilities for multi-dimensional cube queries is an issue of some complexity. In practice, the difficulty of the in- dexing problem is exacerbated by the existence of attribute hierarchies that sub-divide attributes into aggregation layers of varying granularity. In this paper, we present a hierar- chy and caching framework that supports the efficient and transparent manipulation of attribute hierarchies within a parallel ROLAP environment. Experimental results verify that, when compared to the non-hierarchical case, very little overhead is required to handle streams of arbitrary hierar- chical queries. Categories and Subject Descriptors H.2.7.b [Database Management]: Data Warehouse and Repository; H.2.2.a [DatabaseManagement]: AccessMeth- ods General Terms Algorithms Design Performance Keywords Hierarchies, Caching, Data Cubes, Aggregation, Indexing, OLAP, Granularity, Materialization, Parallelization 1. INTRODUCTION Online Analytical Processing (OLAP) has become an im- portant component of contemporary Decision Support Sys- tems (DSS). Central to OLAP is the data cube, a multidi- mensional data model that presents an intuitive cube-like Permission to make......

Words: 760 - Pages: 4

Free Essay

Data Base Management

...1. Data dependence Data illustration incorporates with the requisition function. If there is alteration in the Data, then also there is a difference in the application function. Data independence Data depiction incorporates with operation function. If there is a transition in the Data, it won’t cause a shift in the application program. 2. Structured data It is established data which could efficiently be reclaimed and reserved in the databases as well as warehouses. It assign to the substantial case of the user's situation such as phenomenon and development. Unstructured data It consists of combined use of several media data like pictures, sounds, and video clips. Then, it is reserved as the element of the user's field situation 3. Data It is the illustration of articles and episode which are reserved and acknowledged in the system. It persists in a array of form such as numeric, symbols, 3RQ variables, and so on. For example, database in dr's clinic will have information such as patient name, address, diagnosis, symptoms, and phone number. Information These are the refined data which elevates the information of the specific using it. Data are worthless in their current prospective from so it is pre-refined and illustrated as the information to the user 4. Repository It is the rationalised reserved area for data meaning, table, data relationships and other parts of data system. It......

Words: 689 - Pages: 3

Premium Essay

Benefits of Social Networking

...Chapter 6 Basic data structures A data structure, sometimes called data type, can be thought of as a category of data. Integer is a data category which can only contain integers. String is a data category holding only strings. A data structure not only defines what elements it may contain, it also supports a set of operations on these elements, such as addition or multiplication. Strings and numbers are the core data structures in Python. In this chapter, you’ll see a few more, almost as important, data structures. In the next chapter, you’ll se how you can design your own, customary data structures. The concept of a sequence is so fundamental to programming that I’ve had a very hard time avoiding it so far. And as you, alert and perky, have noticed, I actually haven’t, since I involuntarily had to introduce sequences in Section 4.4 when talking about the for loop. In Python, the word “sequence” covers several phenomena. Strings are sequences of characters, and you heard about those in Chapter 3. In the coming sections, you’ll hear about the two other basic types of sequence supported by Python: Lists and tuples. Later in this chapter, we’ll get around to talking about sets and dictionaries. Strings and integers represent concrete data objects; a string or a number represents true data in itself.1 Lists, tuples and dictionaries are designed to organize other data, to impose structure upon it; they do not necessarily represent true data in their own right. For this reason,......

Words: 18297 - Pages: 74

Free Essay

Gfs Using Soap

...implemented the Google File System, a scalable distributed file system for large distributed data-intensive applications. It provides fault tolerance while running on inexpensive commodity hardware, and it delivers high aggregate performance to a large number of clients. While sharing many of the same goals as previous distributed file systems, our design has been driven by observations of our application workloads and technological environment, both current and anticipated, that reflect a marked departure from some earlier file system assumptions. This has led us to reexamine traditional choices and explore radically different design points. The file system has successfully met our storage needs. It is widely deployed within Google as the storage platform for the generation and processing of data used by our service as well as research and development efforts that require large data sets. The largest cluster to date provides hundreds of terabytes of storage across thousands of disks on over a thousand machines, and it is concurrently accessed by hundreds of clients. In this paper, we present file system interface extensions designed to support distributed applications, discuss many aspects of our design, and report measurements from both micro-benchmarks and real world use. We have designed and implemented the Google File System (GFS) to meet the rapidly growing demands of Google’s data processing needs. GFS shares many of the same goals as previous distributed......

Words: 14789 - Pages: 60

Premium Essay


...should write the MyList class, which is a linked list data structure to store person information. The following functions should be included in the MyList class: • void addLast(String xName, int xAge) - check if the first letter of xName is not 'B' (i.e. xName.charAt(0) != 'B') then add new person with name=xName, age=xAge to the end of the list. • void addFirst(String xName, int xAge) - check if the first letter of xName is not 'B' then add new person with name=xName, age=xAge to the begining of the list. • void addMany(String [] a, int [] b) - this function is given. • void ftraverse(RandomAccessFile f) throws Exception - display all nodes in the file f in format: (name, age). This function is given. • void f1() – Test addLast function. You do not need to edit this function. Your task is to complete the function addLast(String xName, int xAge) function only. With the given data, the content of f1.txt must be the following: (A0,9) (A7,13) (A5,7) (A3,11) (A4,9) (A2,12) (A6,5) (A1,6) • void f2() – Test addFirst function. You do not need to edit this function. Your task is to complete the function addFirst(String xName, int xAge) function only. With the given data, the content of f2.txt must be the following: (A1,6) (A6,5) (A2,12) (A4,9) (A3,11) (A5,7) (A7,13) (A0,9) • void f3() – create MyList object t and using addLast method to add to t all elements having age>xAge, where xAge=4. With the given data, the content of f3.txt must be the......

Words: 349 - Pages: 2

Premium Essay


...should write the MyList class, which is a linked list data structure to store person information. The following functions should be included in the MyList class: • void addLast(string xName, int xAge) - check if the first letter of xName is not 'B' (i.e. != 'B') then add new person with name=xName, age=xAge to the end of the list. • void addFirst(string xName, int xAge) - check if the first letter of xName is not 'B' then add new person with name=xName, age=xAge to the begining of the list. • void ftraverse(ofstream &fou) - display all nodes in the file fou in format: (name, age). This function is given. • void f1() – Test addLast function. You do not need to edit this function. Your task is to complete the function addLast(string xName, int xAge) function only. With the given data, the content of the file f1.txt must be the following:: (A0,9) (A7,13) (A5,7) (A3,11) (A4,9) (A2,12) (A6,5) (A1,6) • void f2() – Test addFirst function. You do not need to edit this function. Your task is to complete the function addFirst(string xName, int xAge) function only. With the given data, the content of the file f2.txt must be the following:: (A1,6) (A6,5) (A2,12) (A4,9) (A3,11) (A5,7) (A7,13) (A0,9) • void f3() – The object MyList h is given. Using addLast method to add to h all elements having age>xAge, where xAge=4. With the given data, the content of the file f3.txt must be the......

Words: 344 - Pages: 2

Free Essay


...CS301 – Data Structures ___________________________________________________________________ Data Structures 1 CS301 – Data Structures ___________________________________________________________________ Data Structures..........................................................................................................1 Lecture No. 01 ............................................................................................................3 Lecture No. 02 ..........................................................................................................12 Lecture No. 03 ..........................................................................................................21 Lecture No. 04 ..........................................................................................................34 Lecture No. 05 ..........................................................................................................49 Lecture No. 06 ..........................................................................................................59 Lecture No. 07 ..........................................................................................................66 Lecture No. 08 ..........................................................................................................73 Lecture No. 09 ..........................................................................................................84 Lecture No. 10 ....................................

Words: 13571 - Pages: 55

Free Essay

Ds Java

...A Practical Introduction to Data Structures and Algorithm Analysis Third Edition (Java) Clifford A. Shaffer Department of Computer Science Virginia Tech Blacksburg, VA 24061 April 16, 2009 Copyright c 2008 by Clifford A. Shaffer. This document is the draft of a book to be published by Prentice Hall and may not be duplicated without the express written consent of either the author or a representative of the publisher. Contents Preface xiii I Preliminaries 1 1 Data Structures and Algorithms 1.1 A Philosophy of Data Structures 1.1.1 The Need for Data Structures 1.1.2 Costs and Benefits 1.2 Abstract Data Types and Data Structures 1.3 Design Patterns 1.3.1 Flyweight 1.3.2 Visitor 1.3.3 Composite 1.3.4 Strategy 1.4 Problems, Algorithms, and Programs 1.5 Further Reading 1.6 Exercises 3 4 4 6 8 12 13 14 15 16 17 19 21 2 Mathematical Preliminaries 2.1 Sets and Relations 2.2 Miscellaneous Notation 2.3 Logarithms 2.4 Summations and Recurrences 25 25 29 31 33 iii iv Contents 2.5 2.6 2.7 2.8 2.9 3 II 4 Recursion Mathematical Proof Techniques 2.6.1 Direct Proof 2.6.2 Proof by Contradiction 2.6.3 Proof by Mathematical Induction Estimating Further Reading Exercises Algorithm Analysis 3.1 Introduction 3.2 Best, Worst, and Average Cases 3.3 A Faster Computer, or a Faster Algorithm? 3.4 Asymptotic Analysis 3.4.1 Upper Bounds 3.4.2 Lower Bounds 3.4.3 Θ Notation 3.4.4......

Words: 30587 - Pages: 123

Free Essay

Non Linear Data Structure

...What is a non-linear datastructure? A non-linear datastrucutre is a datastructure in which the data items in the memory are not allocated contiguously i.e. the data items are dispersed in the memory. The first data item will have a link to the second data item and second data item will have a link to the third data item and so on. Pros • Uses memory efficiently that the free contiguous memory in not an requirement for allocating data items • The length of the data items is not necessary to be known prior to allocation Cons • Overhead of the link to the next data item Linked list: linked list a data structure which stores data in the form of nodes.It does not require linear memory as arrays. Each node contains a data part and a pointer part(a pointer to the next data in the list) link or node is object of a class.there are so many types of linked list 1) single linked list 2)doubly linked list 3)circular linked list. single linked list: here links contains pointer to first data and last data in the list.As said earlier a pointer to the next data. example of a linked list: class node{// all nodes will be the objects of this class public int data; public link next_node;//a pointer to next data } public node(int data){; }//end of constructor public void showdata(){ System.out.println("data= "+data); } }//end of class node After defining class for each node we need to define a class for link list. Link list contains a pointer......

Words: 475 - Pages: 2

Free Essay


...Linked List 1 List vs Arrays Two built-in data structures that can be used to organize data, or to create other data structures: • Lists • Arrays Lists A list is an ordered set of data. It is often used to store objects that are to be processed sequentially. Arrays An array is an indexed set of variables, such as dancer[1], dancer[2], dancer[3],… It is like a set of boxes that hold things. A list is a set of items. An array is a set of variables that each store an item. Arrays and Lists You can see the difference between arrays and lists when you delete items. Arrays and Lists In a list, the missing spot is filled in when something is deleted. Arrays and Lists In an array, an empty variable is left behind when something is deleted. What’s wrong with Array and Why lists? • Disadvantages of arrays as storage data structures: – slow searching in unordered array – slow insertion in ordered array – Fixed size • Linked lists solve some of these problems • Linked lists are general purpose storage data structures and are versatile. Linked Lists A Head B C  • A linked list is a series of connected nodes • Each node contains at least – A piece of data (any type) – Pointer to the next node in the list • Head: pointer to the first node • The last node points to NULL node A data pointer The composition of a Linked List • A linked list is called "linked" because each node in the series has a pointer that......

Words: 2375 - Pages: 10