1 Recursion Simple recursion to traverse lists Recursive data structures and recursive functions.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Chapter 1: INTRODUCTION TO DATA STRUCTURE
Introduction to Algorithms Quicksort
Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
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.
The complexity and correctness of algorithms (with binary trees as an example)
Data Structures: A Pseudocode Approach with C 1 Chapter 5 Contd... Objectives Explain the design, use, and operation of a linear list Implement a linear.
Data Compressor---Huffman Encoding and Decoding. Huffman Encoding Compression Typically, in files and messages, Each character requires 1 byte or 8 bits.
Introduction to Trees. Tree example Consider this program structure diagram as itself a data structure. main readinprintprocess sortlookup.
Searching Kruse and Ryba Ch and 9.6. Problem: Search We are given a list of records. Each record has an associated key. Give efficient algorithm.
CSC1016 Coursework Clarification Derek Mortimer March 2010.
Binary Search Trees Briana B. Morrison Adapted from Alan Eugenio.
1 Specifying Object Interfaces. 2 Major tasks in this stage: --are there any missing attributes or operations? --how can we reduce coupling, make interface.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 10.
CS 206 Introduction to Computer Science II 02 / 11 / 2009 Instructor: Michael Eckmann.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Binary Search Trees CSE, POSTECH. Search Trees Search trees are ideal for implementing dictionaries – Similar or better performance than skip lists and.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
Advanced Data Structures and Algorithms COSC-600 Lecture presentation-6.
9 Priority Queues, Heaps, and Graphs. 9-2 What is a Heap? A heap is a binary tree that satisfies these special SHAPE and ORDER properties: –Its shape.
Chapter 19 - basic definitions - order statistics ( findkth( ) ) - balanced binary search trees - Java implementations Binary Search Trees 1CSCI 3333 Data.
Advanced Algorithms Analysis and Design Lecture 8 (Continue Lecture 7…..) Elementry Data Structures By Engr Huma Ayub Vine.
MA/CSSE 473 Day 13 Permutation Generation. MA/CSSE 473 Day 13 HW 6 due Monday, HW 7 next Thursday, Student Questions Tuesday’s exam Permutation generation.
Chapter 19: Binary Trees. Objectives In this chapter, you will: – Learn about binary trees – Explore various binary tree traversal algorithms – Organize.
ITEC 2620A Introduction to Data Structures
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
“On an Algorithm of Zemlyachenko for Subtree Isomorphism” Yefim Dinitz, Alon Itai, Michael Rodeh (1998) Presented by: Masha Igra, Merav Bukra.
TECH Computer Science Data Abstraction and Basic Data Structures Improving efficiency by building better  Data Structure Object IN  Abstract Data Type.
Chapter 9 Priority Queues, Heaps, Graphs, and Sets.
CS121 Data Structures CS121 © JAS 2004 Tables An abstract table, T, contains table entries that are either empty, or pairs of the form (K, I) where K is.
CMSC 341 B- Trees D. Frey with apologies to Tom Anastasio.
1 Searching Searching in a sorted linked list takes linear time in the worst and average case. Searching in a sorted array takes logarithmic time in the.
Lecture1 introductions and Tree Data Structures 11/12/20151.
Data Structures TREES.
1 Section 2.1 Algorithms. 2 Algorithm A finite set of precise instructions for performing a computation or for solving a problem.
B-trees Eduardo Laber David Sotelo. What are B-trees? Balanced search trees designed for secondary storage devices Similar to AVL-trees but better at.
CHAPTER 8 SEARCHING CSEB324 DATA STRUCTURES & ALGORITHM.
1 5. Abstract Data Structures & Algorithms 5.1 Data Structure Fundamentals.
Binary Search Trees (BST)
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
1 Principles revisited.NET: Two libraries: System.Collections System.Collections.Generics Data Structures and Collections.
Chapter 20: Graphs. Objectives In this chapter, you will: – Learn about graphs – Become familiar with the basic terminology of graph theory – Discover.
1 Modelling using Sequences Sequences The finite sequence constructor Value definitions: enumeration, subsequence Operators on Sequences Case Study: the.
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
Trees A non-linear implementation for collection classes.
CSE 373 Data Structures Lecture 7
Binary Search Trees What is a binary search tree?
Recursion Topic 5.
Top 50 Data Structures Interview Questions
Error Correcting Code.
Binary Search Tree (BST)
Lecture 22 Binary Search Trees Chapter 10 of textbook
Program based on pointers in C.
Structural testing, Path Testing
Teach A level Computing: Algorithms and Data Structures
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Chapter 9 Priority Queues, Heaps, Graphs, and Sets
Data Structures: Segment Trees, Fenwick Trees
Find in a linked list? first last 7  4  3  8 NULL
The Metacircular Evaluator
B- Trees D. Frey with apologies to Tom Anastasio
Searching CLRS, Sections 9.1 – 9.3.
CS 583 Analysis of Algorithms
ITEC 2620M Introduction to Data Structures
Data Structures Using C++ 2E
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

1 Recursion Simple recursion to traverse lists Recursive data structures and recursive functions

2 Recursion At the level of abstraction at which most formal models are developed, the inefficiency of a recursive implementation is not such a major issue. As a result, recursive data types, and recursive functions to traverse them, are comparatively common. Perhaps the simplest case in which recursion is used is in traversing a sequence data structure, e.g. to perform some operation on all of the elements of the sequence. We can also define data structures recursively, e.g. tree structures, and again recursive functions are needed to traverse these structures.

3 Recursion As a first example, consider the following type definitions from the model of a system to track the movement of containers on aircraft for an air freight business. A flight may be modelled as a record with an identifier and a sequence of containers in the flight (representing the linear layout of containers in the hold of an aircraft): Flight :: fid : FlightId cargo : seq of Container Container :: content_type : | | weight : nat There are a number of functions we might wish to define on this structure. Suppose we are asked to record a restriction that the total weight of the cargo on a flight must not exceed 5000 units. Flight :: fid : FlightId cargo : seq of Container inv mk_Flight(fid,cargo) == TotalWeight(cargo) <= 5000

4 Recursion Now we need to define the auxiliary function TotalWeight TotalWeight: (seq of Container) -> nat TotalWeight(s) == if s = nil then 0 else (hd s).weight + TotalWeight(tl s) Note that we must ensure the recursion terminates (just as you always make sure that a loop terminates) and so we include a “base case” which does not lead to a recursive call of the function. Typically the base case relates to a basic element of the data type: an empty or nil value.

5 Recursion Exercise: The XOR operator is used widely in encryption: it calculates the exclusive OR of two sequences of bits. Give a recursive definition of this operator. XOR: (seq of bool) * (seq of bool) -> (seq of bool) What does your function do if the two sequences aren’t the same length?

6 Recursion Exercise: The XOR operator is used widely in encryption: it calculates the exclusive OR of two sequences of bits. Give a recursive definition of this operator. XOR: (seq of bool) * (seq of bool) -> (seq of bool) XOR(p,q)== if p=nil then nil else if q=nil then nil else xor(hd(p),hd(q)):XOR(tl(p), tl(q))) XOR(p,q)== [xor(p[i], q[i]) | i <= min(length(p), length(q))]

7 Recursion Recursion is also possible in type definitions. This is particularly common where tree and graph structures are to be modelled. Example We often have to model representations of more abstract data structures. For example, sets and mappings are quite abstract and may not be available in an implementation language or may be inefficient to use. This example models a set of natural numbers as a binary tree to allow efficient updating and checking. Such a binary tree: has two (possibly nil) branches and a number at each node; and is arranged so that all the numbers in the left branch of a node are less than (and all the numbers in the right branch are greater than) the number in the node. e.g.

8 Recursion The binary tree structure can be modelled as follows: Setrep = [Node] Node :: left : Setrep value : nat right : Setrep inv mk_Node(left,value,right) == forall lv in set gather(left) & lv < value and forall rv in set gather(right) & rv > value To define the invariant, we used an auxiliary function which returns all the numbers stored in a given tree. The definition of this function uses recursion.

9 Recursion The gather function: gather: Setrep -> set of nat gather(sr) == Observe that this function gets us from the concrete representation of the set back to its abstract counterpart. Such functions are called retrieve functions and are used to show that a concrete representation is faithful to its abstract specification.

10 Recursion Exercise Define a function add which, given a number and a Setrep, adds the number at the correct point in the Setrep, returning the updated Setrep.

11 Review Recursion is used in functions that have to traverse larger data structures such as sequences. When defining a recursive function, remember to ensure that there is a base case to guarantee termination. Recursive data types can also be defined to model structures such as tress and graphs. Traversal of such data structures also implies the use of a recursive function.