course
play

Course Objective : to teach you some data structures and associated - PowerPoint PPT Presentation

Course Objective : to teach you some data structures and associated algorithms INF421, Lecture 3 Evaluation : TP not en salle info le 16 septembre, Contrle la fin. Stacks and recursion Note: max( CC, 3 4 CC + 1 4 TP ) Organization : fri


  1. Course Objective : to teach you some data structures and associated algorithms INF421, Lecture 3 Evaluation : TP noté en salle info le 16 septembre, Contrôle à la fin. Stacks and recursion Note: max( CC, 3 4 CC + 1 4 TP ) Organization : fri 26/8, 2/9, 9/9, 16/9, 23/9, 30/9, 7/10, 14/10, 21/10, Leo Liberti amphi 1030-12 (Arago), TD 1330-1530, 1545-1745 (SI31,32,33,34) Books : LIX, ´ Ecole Polytechnique, France 1. Ph. Baptiste & L. Maranget, Programmation et Algorithmique , Ecole Polytechnique (Polycopié), 2006 2. G. Dowek, Les principes des langages de programmation , Editions de l’X, 2008 3. D. Knuth, The Art of Computer Programming , Addison-Wesley, 1997 4. K. Mehlhorn & P . Sanders, Algorithms and Data Structures , Springer, 2008 Website : www.enseignement.polytechnique.fr/informatique/INF421 Contact : liberti@lix.polytechnique.fr (e-mail subject: INF421) INF421, Lecture 3 – p. 1 INF421, Lecture 3 – p. 2 Lecture summary Function calls Stacks and applications Recursion Function calls INF421, Lecture 3 – p. 3 INF421, Lecture 3 – p. 4

  2. What is a function call? Functions essentials A function call is a diversion from the sequential instructions order A recipe is a program, you are the CPU, your kitchen is the memory you need to know where to go next Salad and walnuts recipe you need to store the current instruction address so you can 1. add the salad resume execution once the function terminates 2. add the walnuts call to g f 3. add vinaigrette f calls g : 4. toss and serve g Seems simple enough, but when you get to Step 3 you Assume f calls g and g calls h , and h is currently executing realize that in order to add the vinaigrette you need to In order for f to resume control, g must have terminated first prepare it first! f So you leave everything as is, mix oil and vinegar, add g salt, then resume the recipe from where you’d left it h You just called a function h cannot pass control to f directly INF421, Lecture 3 – p. 5 INF421, Lecture 3 – p. 6 Saving the state Argument passing x a variable in f , and g needs to access it: Every function defines a “naming scope” (denote an f calls g ( x ) entity x defined within a function f by f :: x ) If f calls g , both may define a local variable x , but f :: x Let variable x name a cell with address A x and value V x and g :: x refer to different memory cells Passing by reference: g ( A x ) Before calling g , f must therefore save its current state : if g changes V x then the change is visible in f the name and address of each local variable in f Passing by value: g ( V x ) the address of the instruction just after “call g ” in f if g changes V x then the change is not visible in f When g ends, the current state of f is retrieved, and f resumes This is a model , not the actual implementation used by languages Need a data structure for saving current states In practice, Java behaves as if basic types ( char, int, As function calls are very common, it must be as simple long, float, double ) were passed by value, and and efficient as possible composite types by reference INF421, Lecture 3 – p. 7 INF421, Lecture 3 – p. 8

  3. Passing by reference Passing by value g ( x ) f g ( x ) f 2 1 2 copy ref B x A x A x A x x x executed: x = 2 x executed: x = 2 When g terminates, the new value of x is available to f When g terminates, the new value of x is lost INF421, Lecture 3 – p. 9 INF421, Lecture 3 – p. 10 Current states are saved to a stack f calls g calls h Stacks and applications top CPU is current state of g push executing g ::call h current state of f Memory INF421, Lecture 3 – p. 11 INF421, Lecture 3 – p. 12

  4. Stack Hack the stack Linear data structure Accessible from only one end (top) Operations: add a data node on the top ( push data ) remove a data node from the top ( pop data ) test whether stack is empty Every operation must be O (1) Don’t need insertion/removal from the middle: can implement using arrays Back in 1996, hackers would get into systems by writing disguised code in the execution stack INF421, Lecture 3 – p. 13 INF421, Lecture 3 – p. 14 How does it work? 1/2 How does it work? 2/2 top top . . . . . . A g A g "url" "url" 10 10 h :: x = 1 h :: x = 1 x t x t : : h :: y = 2 h :: y = 2 address A h in g to pass address A h in g to pass control to at end of h control to at end of h u r l 1 A l e o 5 B 6 4 6 4 g :: x = 10 g :: x = 10 : : g :: t = "url" g :: t = "url" t t address A g in f to pass address A g in f to pass address where A g is stored address where A g is stored control to at end of g control to at end of g f :: y = 6 . 2 f :: y = 6 . 2 User input t = "leo5B" changes return addr : : g :: t : user input (e.g. URL from browser) A g = 0x1A64 becomes A ′ = 0x5B64 f :: t = "config" f :: t = "config" Code for g does not check input length in main in main When g ends, CPU jumps to address A ′ � = A g address A f to address A f to User might input strings longer than 3 chars pass control to at end of f pass control to at end of f Set it up so that code at A ′ opens a root shell For example, input "leo5B" Machine hacked bottom bottom INF421, Lecture 3 – p. 15 INF421, Lecture 3 – p. 16

  5. Checking brackets The Tower of Hanoi Given a mathematical sentence with two types of brackets “ () ” and “ [] ”, write a program that checks whether they have been embedded correctly 1. s : the input string 2. for each i from 1 to | s | : (a) if s i is an open bracket, push the corresponding closing bracket on the stack (b) if s i is a closing bracket, pop a char t from the stack: if the stack is empty, error : too many closing brackets if t � = s i , error : closing bracket has wrong type 3. if stack is not empty, error : not enough closing brackets Move stack of discs to different pole, one at a time, no larger over smaller INF421, Lecture 3 – p. 17 INF421, Lecture 3 – p. 18 Code for checking brackets Usefulness input string s ; stack T ; int i = 0 ; while ( i ≤ s. length ) do Today, stacks are provided by Java/C++ libraries, they are implemented if ( s i = ’(’ ) then T. push ( ’)’ ) ; as a subset of operations of lists or vectors. Here are some reasons else if ( s i = ’[’ ) then why you might want to rewrite a stack code T. push ( ’]’ ) ; else if ( s i ∈ { ’)’, ’]’ } ) then You’re a student and learning to program if ( T. isEmpty ()) then You’re writing an interpreter or a compiler error: too many closing brackets; else You’re writing an operating system t = T. pop () ; if ( t � = s i ) then You’re writing some graphics code which must execute error: wrong closing bracket type at i ; blighteningly fast and existing libraries are too slow end if end if You’re a security expert wishing to write an end if unsmashable stack i = i + 1 ; end while You’re me trying to teach you stacks if ( ¬ T. isEmpty ()) then error: not enough closing brackets; end if INF421, Lecture 3 – p. 19 INF421, Lecture 3 – p. 20

  6. Compare iteration and recursion function f () { print "hello" ; while ( true ) do f () ; print "hello" ; Recursion end while } f () ; both programs yield the same infinite loop What are the differences? Why should we bother? INF421, Lecture 3 – p. 21 INF421, Lecture 3 – p. 22 Difference? Forget assignments Termination function f ( n ) { input n ; Make sure your recursions terminate if ( n = 0) then r = 1 return 1 For example: if f ( n ) is recursive, for ( i = 1 to n ) do end if recurse on smaller integers, e.g. f ( n − 1) or f ( n/ 2) r = r × i return n × f ( n − 1) provide “base cases” where you do not recurse, e.g. f (0) or f (1) end for } output r Compare with induction : prove a statement for n = 0 and prove that if it f ( n ) ; holds for all i < n then it holds for n too; conclude it holds for all n Both programs compute n ! Typically, a recursive algorithm f ( n ) is as follows: Iterative version has assignments, recursive version does not if n is a “base case” then Every computable function can be computed by means of {tests, compute f ( n ) directly, do not recurse assignments, iterations} or {tests, recursion} else For language expressivity: “recursion = assignment + iteration” recurse on f ( i ) with some i < n Don’t forget that calling a function implies saving the current state on a stack end if (in recursion there is an implicit assignment of variable values to the stack memory) INF421, Lecture 3 – p. 23 INF421, Lecture 3 – p. 24

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend