A Level Computer Science Topic 9: Data Structures T eaching L ondon C omputing William Marsh School of Electronic Engineering and Computer Science Queen.

Slides:



Advertisements
Similar presentations
Algorithms (and Datastructures) Lecture 3 MAS 714 part 2 Hartmut Klauck.
Advertisements

S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Tree Data Structures &Binary Search Tree 1. Trees Data Structures Tree  Nodes  Each node can have 0 or more children  A node can have at most one parent.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
Main Index Contents 11 Main Index Contents Week 6 – Binary Trees.
Advanced Data Structures
CS 171: Introduction to Computer Science II
Binary Trees Terminology A graph G = is a collection of nodes and edges. An edge (v 1,v 2 ) is a pair of vertices that are directly connected. A path,
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Lists A list is a finite, ordered sequence of data items. Two Implementations –Arrays –Linked Lists.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
Data Structures Data Structures Topic #8. Today’s Agenda Continue Discussing Table Abstractions But, this time, let’s talk about them in terms of new.
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Course Review COMP171 Spring Hashing / Slide 2 Elementary Data Structures * Linked lists n Types: singular, doubly, circular n Operations: insert,
The Most Commonly-used Data Structures
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Important Problem Types and Fundamental Data Structures
Binary Trees Chapter 6.
Data Structures Arrays both single and multiple dimensions Stacks Queues Trees Linked Lists.
Advanced Algorithms Analysis and Design Lecture 8 (Continue Lecture 7…..) Elementry Data Structures By Engr Huma Ayub Vine.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
ECE 103 Engineering Programming Chapter 61 Abstract Data Types Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material.
Information and Computer Sciences University of Hawaii, Manoa
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
Topic 14 The BinaryTree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms.
Representing and Using Graphs
Binary Trees 2 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees.
Trees : Part 1 Section 4.1 (1) Theory and Terminology (2) Preorder, Postorder and Levelorder Traversals.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Binary Tree. Some Terminologies Short review on binary tree Tree traversals Binary Search Tree (BST)‏ Questions.
TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.
CISC220 Fall 2009 James Atlas Dec 07: Final Exam Review.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Binary Search Trees.  Understand tree terminology  Understand and implement tree traversals  Define the binary search tree property  Implement binary.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
1 the BSTree class  BSTreeNode has same structure as binary tree nodes  elements stored in a BSTree are a key- value pair  must be a class (or a struct)
Trees By JJ Shepherd. Introduction Last time we discussed searching and sorting in a more efficient way Divide and Conquer – Binary Search – Merge Sort.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
Chapter 11. Chapter Summary  Introduction to trees (11.1)  Application of trees (11.2)  Tree traversal (11.3)  Spanning trees (11.4)
Trees A non-linear implementation for collection classes.
CSE 373 Data Structures Lecture 7
The Tree ADT.
CC 215 Data Structures Trees
Recursive Objects (Part 4)
Week 6 - Wednesday CS221.
Source Code for Data Structures and Algorithm Analysis in C (Second Edition) – by Weiss
Lecture 18. Basics and types of Trees
Week 11 - Friday CS221.
Hashing Exercises.
CSE 373 Data Structures Lecture 7
i206: Lecture 13: Recursion, continued Trees
COSC2100: Data Structures and Algorithms
CS212: Data Structures and Algorithms
Trees CSE 373 Data Structures.
Graphs Chapter 11 Objectives Upon completion you will be able to:
ITEC 2620M Introduction to Data Structures
Trees Lecture 9 CS2110 – Fall 2009.
Tree.
Trees.
Important Problem Types and Fundamental Data Structures
Trees.
Trees CSE 373 Data Structures.
Introduction to Trees Chapter 6 Objectives
Trees Lecture 10 CS2110 – Spring 2013.
Presentation transcript:

A Level Computer Science Topic 9: Data Structures T eaching L ondon C omputing William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London

Aims Where do lists and dictionaries come from? Understand the problem Introduce the following data structures Linked list Binary search tree Hash sets Graphs

Syllabus – OCR

Syllabus – AQA

Data Structures? “I will, in fact, claim that the difference between a bad programmer and a good one is whether he considers his code or his data structures more important. Bad programmers worry about the code. Good programmers worry about data structures and their relationships.” Linus Torvalds, 2006

Problem: Arrays  Lists Abstractions

Abstraction v Implementation List abstraction Grows and shrinks – insert, remove Index into – lst[n] Stack abstraction (plate stack) Push, pop Simpler than list, as only access ‘top’ Many possible implementations of each abstraction Trade-offs

Lists in Arrays The array cannot grow To insert, we have to shuffle along Indexing is quick Because indexing is quick, there are implementations based on arrays in lists

Aside: Array and LMC Address of array – A – is address of entry 0 Address of A[n] is is A + n Real computers Have registers for addresses Do arithmetic on addresses... n Address of A

Set & Map Abstractions Set Membership Insert Remove Dictionary (Map) Keys are like a set – value attached to each key... Set operations Lookup value is similar to membership Key Value

Linked Lists An implementation of the list abstractions

Linked List Concept Each entry has A value A pointer to the next entry Keep a pointer to the front entry The pointer of the last entry is None bcdef frontback

Linked List Index Count along the list to entry i Return the value pointer = front count = 0 while count < i: pointer  next of current entry count = count + 1 return the value of current entry myList.index(i)

Linked List Update Count along the list to entry index Replace value with new value pointer = front count = 0 while count < idx: pointer  next of currentEntry count = count = 1 currentEntry.value = newValue myList.update(idx, newValue)

Linked List Insert Count along the list to entry idx-1 Insert a new entry Next pointer of current entry points to new entry Next pointer of new entry points to following entry myList.insert(idx, newValue)

Exercise Redraw list after: appending a new entry at the end inserting before entry zero inserting before entry 3 bcdef frontback

Linked List Code class Entry: def __init__(self, v): self.value = v self.next = None def setValue(self, v): self.value = v def getValue(self): return self.value def setNext(self, n): self.next = n def getNext(self): return self.next class List: def __init__(self): self.length = 0 self.first = None def append(self, value): entry = Entry(value) if self.first == None : self.first = entry return p = self.first q = p.getNext() while q != None: p = q q = p.getNext() p.setNext(entry) def index(self, i): count = 0 p = self.first while count < i: p = p.getNext() count = count + 1 return p.getValue()

Complexity of Linked List Indexing is linear: O(n) c.f. array index is O(1) need to do better! Often need to visit every entry in the list e.g. sum, search This is O(n 2 ) if we use indexing Easy to improve this by keeping track of place in list Search is O(n)

Binary Trees A more complex linked structure

Introduction Many uses of (binary) tree Key ideas Linked data structure with 2 (or more) links (c.f. linked list) Rules for organising tree Binary search tree Other uses Heaps Syntax trees

Binary Search Tree All elements to the left of any node are < than all elements to the right Root Right child Left child Leaf

Exercise: Put The Element In 17, 19, 28, 33, 42, 45, 48

Search Binary search E.g. if target is 28: 28 < 47 – go left 28 > 21 – go right What is the complexity of searching a binary tree?

Binary Tree Search Recursive algorithms Find-recursive(key, node): // call initially with node = root if node == None or node.key == key then return node else if key < node.key then return Find-recursive(key, node.left) else return Find-recursive(key, node.right)

Balance and Complexity Complexity depends on balance Left and right sub-trees (nearly) same size Tree no deeper than it need be Balanced Not balanced

Tree Traversal Order of visiting nodes in tree In-order Traverse the left subtree. Visit the root. Traverse the right subtree Pre-order Visit the root. Traverse the left subtree. Traverse the right subtree

Hash Sets

Insight Array are fast – indexing O(1) Map a string to an int, use as an array index hash() in Python Any hashable type can be a dictionary key Ideally, should spread strings out

Hash Table (Set) Look for string S in array at: hash(S) % size Collision Two items share a hash Linked list of items with same size Array length > number of items Array sized increased if table

Many Other Uses of Hashing Cryptography Checking downloads – checksum Checking for changes

Exercise Try Python hash function on strings and on other values Can you hash e.g. a person object?

Graphs

Graph Many problems can be represented by graphs Network connections Web links... Graphs have Nodes and edges Edges can be directed or undirected Edges can be labelled

Graph v Trees Only one path between two nodes in a tree Graph may have Many paths Cycles (loops)

Graph Traversal Depth first traversal Visit children,... then siblings Breadth first traversal Visit siblings before children Algorithms similar to trees traversal, but harder (because of cycles)

Graph Algorithms Shortest paths Final short path through graph with not-negative edge weight Routing in networks Polynomial Longest paths – travelling salesman Intractable

Graph Representations 2-D table of weights Adjacency list 1-D array of lists of neighbours

Exercise Show representation of in both formats

Exercise Show how maze can represented by a graph Maze solved by finding (shortest) path from start to finish

Summary Python has lists and dictionaries built in Data structures to implement these Linked data structures Hashing: magic