Linked Lists (6.5, 16) Linked Lists

Total Page:16

File Type:pdf, Size:1020Kb

Linked Lists (6.5, 16) Linked Lists Linked lists (6.5, 16) Linked lists Inserting and removing elements in the middle of a dynamic array takes O(n) time ● (though inserting at the end takes O(1) time) ● (and you can also delete from the middle in O(1) time if you don't care about preserving the order) A linked list supports inserting and deleting elements from any position in constant time ● But it takes O(n) time to access a specific position in the list Singly-linked lists A singly-linked list is made up of nodes, "here each node contains# ● some data (the node's value) ● a link (reference) to the ne$t node in the list class Node<E> { E data; Node<E> next; } Singly-linked lists %inked-list representation of the list &'(om), “Dick”, “+arry)! ',am)-# %ist itself is .ust a reference to the first node Operations on linked lists // Insert item at front of list void addFirst(E item) // Insert item after another item void addAfter(Node<E> node, E item) // Remove first item void removeFirst() // Remove item after another item void removeAfter(Node<E> node) Example list "##ist<"trin$> Node<"trin$> Node<"trin$> head ! next ! next ! data ! %Tom% data ! %Dic(% Example of addFirst(E item) Calling addFirst(“Ann”)# "##ist<"trin$> Node<"trin$> Node<"trin$> head ! next ! next ! data ! %Tom% data ! %Dic(% Node<"trin$> item.next = head; next ! head = item; data ! "Ann% item Example of addAfter Calling addAfter(tom, “Ann”)# "##ist<"trin$> Node<"trin$> Node<"trin$> head ! next ! next ! data ! %Tom% data ! %Dic(% node Node<"trin$> next = next ! datadata ! =%Ann% "Ann" item.next = node.next; itemitem node.next = item; Example of removeFirst Calling removeFirst()# "##ist<"trin$> Node<"trin$> Node<"trin$> head ! next ! next ! data ! %Tom% data ! %Dic(% node to be head = head.next; removed Example of removeAfter node to be Calling removeAfter(tom)# removed "##ist<"trin$> Node<"trin$> Node<"trin$> head ! next ! next ! data ! %Tom% data ! %Dic(% node Node<"trin$> next ! data ! "Ann% node.next = node.next.next; A problem It's bad A0I design to need both addFirst and addAfter (like"ise removeFirst and removeAfter): ● (wice as much code to "rite 1 twice as many places to introduce bugs! ● Users of the list library will need special cases in their code for dealing with the first node Idea# add a header node! a fake node that sits at the front of the list but doesn't contain any data Instead of addFirst(x)! we can do addAfter(headerNode, x) List with header node (16" .1) If "e "ant to add 'Ann” before '(om), we can do addAfter(head, “Ann”) "##ist<"trin$> Node<"trin$> Node<"trin$> Node<"trin$> head ! next ! next ! next ! null data = data ! %Tom% data ! %Dic(% 4e header node! #o$bly-linked lists In a singly-linked list you can only go forwards through the list# ● If you're at a node, and want to find the previous node, too bad2 Only way is to search forward from the beginning of the list In a doubly-linked list! each node has a link to the ne$t and the previous nodes 5ou can in O(1) time# ● go forwards and backwards through the list ● insert a node before or after the current one ● modify or delete the current node 4e “classic) data structure for se6uential access A do$bly-linked list 4e list itself 7ach node links to links to the first the ne$t and the and last nodes previous node %nsertion and deletion in do$bly- linked lists Similar to singly-linked lists, but you have to update the prev pointer too8 (o delete the current node the idea is# node.next.-rev ! node+-rev; node.-rev.next ! node+next; Node<String> Node<"trin$> Node<"trin$> next ! next ! next = prev = -rev ! prev = data = )&om” data ! "'ic(% data = %Ann% %nsertion and deletion in do$bly- linked lists, 'ontinued (o delete the current node the idea is# node+next+-rev ! node+-rev; node+-rev+next ! node+next; But this CRA,+7, if we try to delete the first node! since then node+-rev !! n,ll! Also! if "e delete the first node! we need to update the list object's head8 %ots and lots of special cases for all operations# ● :hat if the node is the first node; ● :hat if the node is the last node; ● :hat if the list only has one element so the node is both the first and the last node; (etting rid of the special 'ases +ow can "e get rid of these special cases? One idea (see book): use a header node like for singly linked lists, but also a footer node8 ● head and tail will point at the header and footer node ● <o data node will have n,ll as its next or -rev ● All special cases gone! ● Small problem: allocates two extra nodes per list A cute solution: circularly-linked list with header node )ir'$larly-linked list with header node #inked#ist <"trin$> Node<"trin$> head ! next ! -rev ! data ! %Tom% Node<String> Node<"trin$> next ! next ! prev ! -rev ! data ! data ! %Dic(% Node<"trin$> +ere is the next ! header node prev ! ('prev” links data ! ".arry% not sho"n) )ir'$larly-linked list with header node :orks out quite nicely! ● head.next is the first element in the list ● head.-rev is the last element ● you never need to update head ● no node's next or -rev is ever n,ll ● so no special cases2 5ou can even make do "ithout the header node – then you have one special case! "hen you need to update head Stacks and lists $sing linked lists 5ou can implement a stack using a linked list# ● push# add to front of list ● pop: remove from front of list 5ou can also implement a queue: ● en6ueue# add to rear of list ● de6ueue# remove from front of list A *$eue as a singly-linked list :e can implement a queue as a singly linked list with an e$tra rear pointer# :e en6ueue elements by adding them to the back of the list# ● ,et rear.next to the ne" node ● 3pdate rear so it points to the ne" node Linked lists vs dynamic arrays *ynamic arrays# ● have O(1) random access (get and set) ● have amortised O(1) insertion at end ● have O(n) insertion and deletion in middle %inked lists# ● have O(n) random access ● have O(1) se6uential access ● have O(1) insertion in an arbitrary place (but you have to find that place first) /omplement each other! +hat's the problem with this- int s,m(Lin(ed#ist<Integer> list) { int total = 0; for (int i = 0; i < list+si1e(); i2+) total 2! list+$et(i); ret,rn total; } list8get is O(n) – so the whole thing is O(n=)! .etter! int s,m(Lin(ed#ist<Integer> list) { int total = 0; for (int i: list) total 2! i; ret,rn total; } Remember – linked lists are for sequential access only Linked lists 0 summary 0rovide sequential access to a list ● ,ingly-linked 1 can only go for"ards ● *oubly linked 1 can go for"ards or back"ards Many variations 1 header nodes! circular lists – but they all implement the same abstract data type (interface) Can insert or delete or modify a node in O(1) time But unlike arrays, random access is O(n) ?ava: LinkedList<E> class Hash tables (19.1 – 19.3, 19.5 – 19.6) 1ash tables naïvely A hash table implements a set or map 4e plan# take an array of si@e k *efine a hash function that maps values to indices in the range {B!888!k-1C ● 7$ample# if the values are integers! hash function might be h(n) = n mod k (o find, insert or remove a value x, put it in index h(x) of the array Hash tables naïvely, example Implementing a set of integers, suppose "e take a hash table of si@e D and a hash function h(n) = n mod 5 B 1 = F E This hash table contains 3 4 5 AD! G! 17} Similarly! if we Inserting 1E gives# "anted to find G! B 1 = F E "e would look it 3 4 5 14 up in inde$ 3 A problem 4is naIve idea doesn't "ork8 :hat if "e "ant to insert 1= into the set; B 1 = F E 3 4 5 :e should store 1= at index 2! but there's already something there! 4is is called a collision 6he problem with naïve hash tables <aIve hash tables have t"o problems# 1. Sometimes t"o values have the same hash – this is called a collision ● ("o "ays of avoiding collisions! chaining and probing – "e "ill see them later =. The hash function is specific to a particular si@e of array ● Allo" the hash function to return an arbitrary integer and then take it modulo the array size# h(x) = x.hashCode() mod array.si!e Avoiding 'ollisions: chaining Instead of an array of elements, have an array of linked lists (o add an element, calculate its hash and insert it into the list at that inde$ B 1 = F E 3 4 5 Avoiding 'ollisions: chaining Instead of an array of elements, have an array of linked lists (o add an element, calculate its hash and insert it into the list at that inde$ B 1 = F E Inserting 1= into the table 3 4 5 8 9erforman'e of chained hash tables If the linked lists are small! chained hash tables are fast ● If the size is bounded! operations are O(1) time But if they get big! everything gets slo" Observation 1: the array must be big enough ● If the hash table gets too full (a high load factor)! allocate a ne" array of about t"ice the si@e (rehashing) Observation =# the hash function must evenly distribute the elements! ● If everything has the same hash code! all operations are O(n) #efining a good hash fun'tion :hat is wrong "ith the following hash function on strings; "dd together the character code of each character in the string (character code of a J KH! b = KG! c = 99 etc8) >aps e8g.
Recommended publications
  • Application of TRIE Data Structure and Corresponding Associative Algorithms for Process Optimization in GRID Environment
    Application of TRIE data structure and corresponding associative algorithms for process optimization in GRID environment V. V. Kashanskya, I. L. Kaftannikovb South Ural State University (National Research University), 76, Lenin prospekt, Chelyabinsk, 454080, Russia E-mail: a [email protected], b [email protected] Growing interest around different BOINC powered projects made volunteer GRID model widely used last years, arranging lots of computational resources in different environments. There are many revealed problems of Big Data and horizontally scalable multiuser systems. This paper provides an analysis of TRIE data structure and possibilities of its application in contemporary volunteer GRID networks, including routing (L3 OSI) and spe- cialized key-value storage engine (L7 OSI). The main goal is to show how TRIE mechanisms can influence de- livery process of the corresponding GRID environment resources and services at different layers of networking abstraction. The relevance of the optimization topic is ensured by the fact that with increasing data flow intensi- ty, the latency of the various linear algorithm based subsystems as well increases. This leads to the general ef- fects, such as unacceptably high transmission time and processing instability. Logically paper can be divided into three parts with summary. The first part provides definition of TRIE and asymptotic estimates of corresponding algorithms (searching, deletion, insertion). The second part is devoted to the problem of routing time reduction by applying TRIE data structure. In particular, we analyze Cisco IOS switching services based on Bitwise TRIE and 256 way TRIE data structures. The third part contains general BOINC architecture review and recommenda- tions for highly-loaded projects.
    [Show full text]
  • CS 106X, Lecture 21 Tries; Graphs
    CS 106X, Lecture 21 Tries; Graphs reading: Programming Abstractions in C++, Chapter 18 This document is copyright (C) Stanford Computer Science and Nick Troccoli, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Julie Zelenski, Jerry Cain, Eric Roberts, Mehran Sahami, Stuart Reges, Cynthia Lee, Marty Stepp, Ashley Taylor and others. Plan For Today • Tries • Announcements • Graphs • Implementing a Graph • Representing Data with Graphs 2 Plan For Today • Tries • Announcements • Graphs • Implementing a Graph • Representing Data with Graphs 3 The Lexicon • Lexicons are good for storing words – contains – containsPrefix – add 4 The Lexicon root the art we all arts you artsy 5 The Lexicon root the contains? art we containsPrefix? add? all arts you artsy 6 The Lexicon S T A R T L I N G S T A R T 7 The Lexicon • We want to model a set of words as a tree of some kind • The tree should be sorted in some way for efficient lookup • The tree should take advantage of words containing each other to save space and time 8 Tries trie ("try"): A tree structure optimized for "prefix" searches struct TrieNode { bool isWord; TrieNode* children[26]; // depends on the alphabet }; 9 Tries isWord: false a b c d e … “” isWord: true a b c d e … “a” isWord: false a b c d e … “ac” isWord: true a b c d e … “ace” 10 Reading Words Yellow = word in the trie A E H S / A E H S A E H S A E H S / / / / / / / / A E H S A E H S A E H S A E H S / / / / / / / / / / / / A E H S A E H S A E H S / / / / / / /
    [Show full text]
  • Introduction to Linked List: Review
    Introduction to Linked List: Review Source: http://www.geeksforgeeks.org/data-structures/linked-list/ Linked List • Fundamental data structures in C • Like arrays, linked list is a linear data structure • Unlike arrays, linked list elements are not stored at contiguous location, the elements are linked using pointers Array vs Linked List Why Linked List-1 • Advantages over arrays • Dynamic size • Ease of insertion or deletion • Inserting a new element in an array of elements is expensive, because room has to be created for the new elements and to create room existing elements have to be shifted For example, in a system if we maintain a sorted list of IDs in an array id[]. id[] = [1000, 1010, 1050, 2000, 2040] If we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 • Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved Why Linked List-2 • Drawbacks of Linked List • Random access is not allowed. • Need to access elements sequentially starting from the first node. So we cannot do binary search with linked lists • Extra memory space for a pointer is required with each element of the list Representation in C • A linked list is represented by a pointer to the first node of the linked list • The first node is called head • If the linked list is empty, then the value of head is null • Each node in a list consists of at least two parts 1.
    [Show full text]
  • University of Cape Town Declaration
    The copyright of this thesis vests in the author. No quotation from it or information derived from it is to be published without full acknowledgementTown of the source. The thesis is to be used for private study or non- commercial research purposes only. Cape Published by the University ofof Cape Town (UCT) in terms of the non-exclusive license granted to UCT by the author. University Automated Gateware Discovery Using Open Firmware Shanly Rajan Supervisor: Prof. M.R. Inggs Co-supervisor: Dr M. Welz University of Cape Town Declaration I understand the meaning of plagiarism and declare that all work in the dissertation, save for that which is properly acknowledged, is my own. It is being submitted for the degree of Master of Science in Engineering in the University of Cape Town. It has not been submitted before for any degree or examination in any other university. Signature of Author . Cape Town South Africa May 12, 2013 University of Cape Town i Abstract This dissertation describes the design and implementation of a mechanism that automates gateware1 device detection for reconfigurable hardware. The research facilitates the pro- cess of identifying and operating on gateware images by extending the existing infrastruc- ture of probing devices in traditional software by using the chosen technology. An automated gateware detection mechanism was devised in an effort to build a software system with the goal to improve performance and reduce software development time spent on operating gateware pieces by reusing existing device drivers in the framework of the chosen technology. This dissertation first investigates the system design to see how each of the user specifica- tions set for the KAT (Karoo Array Telescope) project in [28] could be achieved in terms of design decisions, toolchain selection and software modifications.
    [Show full text]
  • Linux Kernel and Driver Development Training Slides
    Linux Kernel and Driver Development Training Linux Kernel and Driver Development Training © Copyright 2004-2021, Bootlin. Creative Commons BY-SA 3.0 license. Latest update: October 9, 2021. Document updates and sources: https://bootlin.com/doc/training/linux-kernel Corrections, suggestions, contributions and translations are welcome! embedded Linux and kernel engineering Send them to [email protected] - Kernel, drivers and embedded Linux - Development, consulting, training and support - https://bootlin.com 1/470 Rights to copy © Copyright 2004-2021, Bootlin License: Creative Commons Attribution - Share Alike 3.0 https://creativecommons.org/licenses/by-sa/3.0/legalcode You are free: I to copy, distribute, display, and perform the work I to make derivative works I to make commercial use of the work Under the following conditions: I Attribution. You must give the original author credit. I Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. I For any reuse or distribution, you must make clear to others the license terms of this work. I Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. Document sources: https://github.com/bootlin/training-materials/ - Kernel, drivers and embedded Linux - Development, consulting, training and support - https://bootlin.com 2/470 Hyperlinks in the document There are many hyperlinks in the document I Regular hyperlinks: https://kernel.org/ I Kernel documentation links: dev-tools/kasan I Links to kernel source files and directories: drivers/input/ include/linux/fb.h I Links to the declarations, definitions and instances of kernel symbols (functions, types, data, structures): platform_get_irq() GFP_KERNEL struct file_operations - Kernel, drivers and embedded Linux - Development, consulting, training and support - https://bootlin.com 3/470 Company at a glance I Engineering company created in 2004, named ”Free Electrons” until Feb.
    [Show full text]
  • 4 Hash Tables and Associative Arrays
    4 FREE Hash Tables and Associative Arrays If you want to get a book from the central library of the University of Karlsruhe, you have to order the book in advance. The library personnel fetch the book from the stacks and deliver it to a room with 100 shelves. You find your book on a shelf numbered with the last two digits of your library card. Why the last digits and not the leading digits? Probably because this distributes the books more evenly among the shelves. The library cards are numbered consecutively as students sign up, and the University of Karlsruhe was founded in 1825. Therefore, the students enrolled at the same time are likely to have the same leading digits in their card number, and only a few shelves would be in use if the leadingCOPY digits were used. The subject of this chapter is the robust and efficient implementation of the above “delivery shelf data structure”. In computer science, this data structure is known as a hash1 table. Hash tables are one implementation of associative arrays, or dictio- naries. The other implementation is the tree data structures which we shall study in Chap. 7. An associative array is an array with a potentially infinite or at least very large index set, out of which only a small number of indices are actually in use. For example, the potential indices may be all strings, and the indices in use may be all identifiers used in a particular C++ program.Or the potential indices may be all ways of placing chess pieces on a chess board, and the indices in use may be the place- ments required in the analysis of a particular game.
    [Show full text]
  • Implementing the Map ADT Outline
    Implementing the Map ADT Outline ´ The Map ADT ´ Implementation with Java Generics ´ A Hash Function ´ translation of a string key into an integer ´ Consider a few strategies for implementing a hash table ´ linear probing ´ quadratic probing ´ separate chaining hashing ´ OrderedMap using a binary search tree The Map ADT ´A Map models a searchable collection of key-value mappings ´A key is said to be “mapped” to a value ´Also known as: dictionary, associative array ´Main operations: insert, find, and delete Applications ´ Store large collections with fast operations ´ For a long time, Java only had Vector (think ArrayList), Stack, and Hashmap (now there are about 67) ´ Support certain algorithms ´ for example, probabilistic text generation in 127B ´ Store certain associations in meaningful ways ´ For example, to store connected rooms in Hunt the Wumpus in 335 The Map ADT ´A value is "mapped" to a unique key ´Need a key and a value to insert new mappings ´Only need the key to find mappings ´Only need the key to remove mappings 5 Key and Value ´With Java generics, you need to specify ´ the type of key ´ the type of value ´Here the key type is String and the value type is BankAccount Map<String, BankAccount> accounts = new HashMap<String, BankAccount>(); 6 put(key, value) get(key) ´Add new mappings (a key mapped to a value): Map<String, BankAccount> accounts = new TreeMap<String, BankAccount>(); accounts.put("M",); accounts.put("G", new BankAcnew BankAccount("Michel", 111.11)count("Georgie", 222.22)); accounts.put("R", new BankAccount("Daniel",
    [Show full text]
  • Algorithms & Data Structures: Questions and Answers: May 2006
    Algorithms & Data Structures: Questions and Answers: May 2006 1. (a) Explain how to merge two sorted arrays a1 and a2 into a third array a3, using diagrams to illustrate your answer. What is the time complexity of the array merge algorithm? (Note that you are not asked to write down the array merge algorithm itself.) [Notes] First compare the leftmost elements in a1 and a2, and copy the lesser element into a3. Repeat, ignoring already-copied elements, until all elements in either a1 or a2 have been copied. Finally, copy all remaining elements from either a1 or a2 into a3. Loop invariant: left1 … i–1 i … right1 a1 already copied still to be copied left2 … j–1 j … right2 a2 left left+1 … k–1 k … right–1 right a3 already copied unoccupied Time complexity is O(n), in terms of copies or comparisons, where n is the total length of a1 and a2. (6) (b) Write down the array merge-sort algorithm. Use diagrams to show how this algorithm works. What is its time complexity? [Notes] To sort a[left…right]: 1. If left < right: 1.1. Let mid be an integer about midway between left and right. 1.2. Sort a[left…mid]. 1.3. Sort a[mid+1…right]. 1.4. Merge a[left…mid] and a[mid+1…right] into an auxiliary array b. 1.5. Copy b into a[left…right]. 2. Terminate. Invariants: left mid right After step 1.1: a unsorted After step 1.2: a sorted unsorted After step 1.3: a sorted sorted After step 1.5: a sorted Time complexity is O(n log n), in terms of comparisons.
    [Show full text]
  • Highly Parallel Fast KD-Tree Construction for Interactive Ray Tracing of Dynamic Scenes
    EUROGRAPHICS 2007 / D. Cohen-Or and P. Slavík Volume 26 (2007), Number 3 (Guest Editors) Highly Parallel Fast KD-tree Construction for Interactive Ray Tracing of Dynamic Scenes Maxim Shevtsov, Alexei Soupikov and Alexander Kapustin† Intel Corporation Figure 1: Dynamic scenes ray traced using parallel fast construction of kd-tree. The scenes were rendered with shadows, 1 TM reflection (except HAND) and textures at 512x512 resolution on a 2-way Intel °R Core 2 Duo machine. a) HAND - a static model of a man with a dynamic hand; 47K static and 8K dynamic triangles; 2 lights; 46.5 FPS. b) GOBLIN - a static model of a hall with a dynamic model of a goblin; 297K static and 153K dynamic triangles; 2 lights; 9.2 FPS. c) BAR - a static model of bar Carta Blanca with a dynamic model of a man; 239K static and 53K dynamic triangles; 2 lights; 12.6 FPS. d) OPERA TEAM - a static model of an opera house with a dynamic model of 21 men without instancing; 78K static and 1105K dynamic triangles; 4 lights; 2.0 FPS. Abstract We present a highly parallel, linearly scalable technique of kd-tree construction for ray tracing of dynamic ge- ometry. We use conventional kd-tree compatible with the high performing algorithms such as MLRTA or frustum tracing. Proposed technique offers exceptional construction speed maintaining reasonable kd-tree quality for ren- dering stage. The algorithm builds a kd-tree from scratch each frame, thus prior knowledge of motion/deformation or motion constraints are not required. We achieve nearly real-time performance of 7-12 FPS for models with 200K of dynamic triangles at 1024x1024 resolution with shadows and textures.
    [Show full text]
  • Singly-Linked Listslists
    Singly-LinkedSingly-Linked ListsLists © 2011 John Wiley & Sons, Data Structures and Algorithms Using Python, by Rance D. Necaise. Modifications by Nathan Sprague LinkedLinked StructureStructure Constructed using a collection of objects called nodes. Each node contains data and at least one reference or link to another node. Linked list – a linked structure in which the nodes are linked together in linear order. © 2011 John Wiley & Sons, Data Structures and Algorithms Using Python, by Rance D. Necaise. Linked Structures – 2 LinkedLinked ListList Terms: head – first node in the list. tail – last node in the list; link field has a null reference. self._ © 2011 John Wiley & Sons, Data Structures and Algorithms Using Python, by Rance D. Necaise. Linked Structures – 3 LinkedLinked ListList Most nodes have no name; they are referenced via the link of the preceding node. head reference – the first node must be named or referenced by an external variable. Provides an entry point into the linked list. An empty list is indicated by a null head reference. self._ © 2011 John Wiley & Sons, Data Structures and Algorithms Using Python, by Rance D. Necaise. Linked Structures – 4 SinglySingly LinkedLinked ListList A linked list in which each node contains a single link field and allows for a complete linear order traversal from front to back. self._ © 2011 John Wiley & Sons, Data Structures and Algorithms Using Python, by Rance D. Necaise. Linked Structures – 5 NodeNode DefinitionDefinition The nodes are constructed from a simple storage class: class ListNode: def __init__(self, data, next_node): self.data = data self.next = next_node © 2011 John Wiley & Sons, Data Structures and Algorithms Using Python, by Rance D.
    [Show full text]
  • Prefix Hash Tree an Indexing Data Structure Over Distributed Hash
    Prefix Hash Tree An Indexing Data Structure over Distributed Hash Tables Sriram Ramabhadran ∗ Sylvia Ratnasamy University of California, San Diego Intel Research, Berkeley Joseph M. Hellerstein Scott Shenker University of California, Berkeley International Comp. Science Institute, Berkeley and and Intel Research, Berkeley University of California, Berkeley ABSTRACT this lookup interface has allowed a wide variety of Distributed Hash Tables are scalable, robust, and system to be built on top DHTs, including file sys- self-organizing peer-to-peer systems that support tems [9, 27], indirection services [30], event notifi- exact match lookups. This paper describes the de- cation [6], content distribution networks [10] and sign and implementation of a Prefix Hash Tree - many others. a distributed data structure that enables more so- phisticated queries over a DHT. The Prefix Hash DHTs were designed in the Internet style: scala- Tree uses the lookup interface of a DHT to con- bility and ease of deployment triumph over strict struct a trie-based structure that is both efficient semantics. In particular, DHTs are self-organizing, (updates are doubly logarithmic in the size of the requiring no centralized authority or manual con- domain being indexed), and resilient (the failure figuration. They are robust against node failures of any given node in the Prefix Hash Tree does and easily accommodate new nodes. Most impor- not affect the availability of data stored at other tantly, they are scalable in the sense that both la- nodes). tency (in terms of the number of hops per lookup) and the local state required typically grow loga- Categories and Subject Descriptors rithmically in the number of nodes; this is crucial since many of the envisioned scenarios for DHTs C.2.4 [Comp.
    [Show full text]
  • Hash Tables & Searching Algorithms
    Search Algorithms and Tables Chapter 11 Tables • A table, or dictionary, is an abstract data type whose data items are stored and retrieved according to a key value. • The items are called records. • Each record can have a number of data fields. • The data is ordered based on one of the fields, named the key field. • The record we are searching for has a key value that is called the target. • The table may be implemented using a variety of data structures: array, tree, heap, etc. Sequential Search public static int search(int[] a, int target) { int i = 0; boolean found = false; while ((i < a.length) && ! found) { if (a[i] == target) found = true; else i++; } if (found) return i; else return –1; } Sequential Search on Tables public static int search(someClass[] a, int target) { int i = 0; boolean found = false; while ((i < a.length) && !found){ if (a[i].getKey() == target) found = true; else i++; } if (found) return i; else return –1; } Sequential Search on N elements • Best Case Number of comparisons: 1 = O(1) • Average Case Number of comparisons: (1 + 2 + ... + N)/N = (N+1)/2 = O(N) • Worst Case Number of comparisons: N = O(N) Binary Search • Can be applied to any random-access data structure where the data elements are sorted. • Additional parameters: first – index of the first element to examine size – number of elements to search starting from the first element above Binary Search • Precondition: If size > 0, then the data structure must have size elements starting with the element denoted as the first element. In addition, these elements are sorted.
    [Show full text]