Data Structures and Analysis (COMP 410)

Slides:



Advertisements
Similar presentations
The University of Adelaide, School of Computer Science
Advertisements

Recursion CS 367 – Introduction to Data Structures.
Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
Lecture 10: Heap Management CS 540 GMU Spring 2009.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
Stacks and HeapsCS-3013 A-term A Short Digression on Stacks and Heaps CS-3013 Operating Systems A-term 2008 (Slides include materials from Modern.
Digression on Stack and Heaps CS-502 (EMC) Fall A Short Digression on Stacks and Heaps CS-502, Operating Systems Fall 2009 (EMC) (Slides include.
1 Chapter 7: Runtime Environments. int * larger (int a, int b) { if (a > b) return &a; //wrong else return &b; //wrong } int * larger (int *a, int *b)
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Programming with Recursion
Run-Time Storage Organization
1 Pertemuan 20 Run-Time Environment Matakuliah: T0174 / Teknik Kompilasi Tahun: 2005 Versi: 1/6.
Recursion.
Run time vs. Compile time
Overview C programming Environment C Global Variables C Local Variables Memory Map for a C Function C Activation Records Example Compilation.
Fall 2009ACS-1805 Ron McFadyen1 Ch 8 Recursion Recursion occurs when a method (or function) calls itself.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Stacks and HeapsCS-502 Fall A Short Digression Stacks and Heaps CS-502, Operating Systems Fall 2007 (Slides include materials from Operating System.
David Stotts Computer Science Department UNC Chapel Hill.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II CS 241 – Computer Programming.
David Stotts Computer Science Department UNC Chapel Hill.
CSE 425: Control Abstraction I Functions vs. Procedures It is useful to differentiate functions vs. procedures –Procedures have side effects but usually.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
RUNTIME ENVIRONMENT AND VARIABLE BINDINGS How to manage local variables.
1 Recursion. 2 A process by which a function calls itself repeatedly  Either directly. X calls X  Or cyclically in a chain. X calls Y, and Y calls X.
David Stotts Computer Science Department UNC Chapel Hill.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Run-Time Environments Presented By: Seema Gupta 09MCA102.
Code Generation Instruction Selection Higher level instruction -> Low level instruction Register Allocation Which register to assign to hold which items?
Recursion Powerful Tool
Programming with Recursion
Recursion.
CS314 – Section 5 Recitation 9
Recursion.
Chapter 14 Functions.
CS314 – Section 5 Recitation 10
Chapter 8: Recursion Data Structures in Java: From Abstract Data Types to the Java Collections Framework by Simon Gray.
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Run-Time Environments Chapter 7
Data Structures and Algorithms
Scope and Code Generation
CS 215 Final Review Ismail abumuhfouz Fall 2014.
Memory Management © 2004, D. J. Foreman.
Procedures (Functions)
Programming with Recursion
Recursion 12-Nov-18.
Data Structures and Analysis (COMP 410)
Stacks & Recursion.
Recursion 2-Dec-18.
The University of Adelaide, School of Computer Science
UNIT V Run Time Environments.
CSC 143 Recursion.
Yan Shi CS/SE 2630 Lecture Notes
Recursion 23-Apr-19.
Chapter 18 Recursion.
Recurrences.
CS210- Lecture 3 Jun 6, 2005 Announcements
RUN-TIME STORAGE Chuen-Liang Chen Department of Computer Science
Run-time environments
Implementing Functions: Overview
Presentation transcript:

Data Structures and Analysis (COMP 410) David Stotts Computer Science Department UNC Chapel Hill

The Big Six Functions (advanced) 0. data (types, simple information) 1. data storage (variables, assignment) 2. data retrieval (expressions, evaluation) 3. repetition (loops) 4. decision making (conditionals) 5. procedure abstraction (functions) 6. data abstraction (arrays) 7. objects: all-the-above, wrapped up

Function call We are by now familiar with calling a function to get some work done distance = calcMiles ( speed, time ); One function can call another function to help get its own job done We are already doing this… myMain function calls your other functions

Trace Calls and Returns function myMain() { var result = cube(4) ; alert(result); return result; } function cube (n) { return n*n*n ; } myMain function is called when button clicked cube function is called by myMain cube returns alert function is called by myMain alert returns

Calling Tree function calls create a “tree” of memory maps (“root” at top, “leaves” at the bottom) myMain ( ) alert() cube() call (from button) return (to HTML page) return return call call alert memory map goes away Cube memory map goes away

Another Example function myMain() { var result = mash(3) ; alert(result); return result; } function mash (n) { return cube(2*n) + 5; } function cube (n) { return n*n*n ; } calls myMain myMain calls mash mash calls cube cube returns then mash returns 3 active function calls, memory maps

Calling Tree myMain ( ) alert() cube() mash() return (to HTML page) call (from button) return call return mash memory map goes away call alert memory map goes away return call Cube memory map goes away

So … Functions can call Functions Ok, it’s brain bending time Can a function call itself ? Yes it can, and it is very useful A function that calls itself is “recursive” Computing with a self-calling function is called “recursion”

Recursion Root of “recursive” is “occur again” A recursive function has a call to its own name in its code body function doTask ( n ) { … x = doTask (n-1); // parameter is smaller return result; }

Recursion Computer scientists love recursion. We are twisted people. Easy to entertain. It has been known for programming books to include a joke entry in their index like this: Recursion, see Recursion. Page 269, index of C language manual says recursion 86, 139, 141, 182, 202, 269

A well known “myth” recursive tall turtle tale In our favored version, an Eastern guru affirms that the earth is supported on the back of a tiger. When asked what supports the tiger, he says it stands upon an elephant; and when asked what supports the elephant he says it is a giant turtle. When asked, finally, what supports the giant turtle, he is briefly taken aback, but quickly replies "Ah, after that it is turtles all the way down." Antonin Scalia, footnote in Rapanos vs. United States, 2006

"What is reflected in a mirror which is reflected in a mirror?"

This is infinite recursion… Not quite what we want in programming

Consider the call “tree” myMain calls doTask …. its turtles all the way down the calling has to stop somehow… or the program will run forever

We like finite We need the recursion to end at some point We need an armadillo in the pile

Where is the armadillo? We write a recursive function by following a very specific pattern base case, then recursive case Base case: the problem is so small the solution is easy with no recursive call. Base case ends the recursion Base case is our armadillo Recursive case: we call the function again but the parameter makes a “smaller” problem. Recursion stops when the smaller problem becomes the base case

Factorial in Math Classic recursive definition… has base case and recursive case… “recurrence equation” in math fact(1) = 1 (the base case) fact(2) = 2 * 1 = 2 * fact(1) fact(3) = 3 * ( 2 * 1 ) = 3 * fact(2) fact(4) = 4 * 3 * ( 2 * 1 ) = 4 * fact(3) etc. In general fact(n) = 1 , if n is 1 base case n * fact ( n-1 ) , otherwise recurrence

Factorial program function factorial ( n ) { Coding pattern reflects the parts of the definition function factorial ( n ) { if (n==1) return 1 ; // base case // the armadillo at the bottom else { // the recursive call // the parameter must be smaller // we solve a smaller problem, then use // that result to solve the current problem return n* factorial ( n - 1 ) ; }

Summation program function sum ( n ) { Coding pattern reflects the parts of the definition function sum ( n ) { if (n==1) return 1 ; // base case, the armadillo else { return n + sum ( n - 1 ) ; } } if (n==1) return 1; if (n==2) return 3; if (n==3) return 6; return n+sum(n-1);

Summation program function sum ( n ) { switch (n) { Coding pattern reflects the parts of the definition function sum ( n ) { switch (n) { case 1: return 1; // armadillo case 2: return 3; // another armadillo case 3: return 6; // dillo default: return n + sum(n-1); // recursion }

Iteration = Recursion Recursion is a notational convenience It does not create new computational power Any loop can be expressed as a recursion and… Any recursion can be expressed as a loop

Iteration = Recursion function sum ( n ) { // non recursive var acc = 0; for (var i=1; i<=n; i++) { acc = acc + i ; } return acc; function sum ( n ) { // recursive if (n==1) return 1 ; return n + sum(n-1) ;

Iteration == Recursion function factorial ( n ) { // non recursive var acc = 1; for (var i=1; i<=n; i++) { acc = acc * i ; } return acc; function factorial ( n ) { // recursive if (n==1) return 1 ; return n * factorial(n-1) ;

Run-time System The “insides” of a programming language… the mechanisms needed to make abstractions like variables, objects, function definitions, function calls, scope… make them work and deliver results when the code is executed Two main dynamic memory “piles”: -- The Stack (func call-return management) -- The Heap (for “new” calls, objects) Function calls need what we refer to as a “call frame” or “stack frame” or an “activation record”

Call Frame Every method/function has a call frame… a template for the dynamic memory needed for the function to execute Frame contains space for all parameters, all local variables, bookkeeping information like return address (where is the code calling the function) When a function is called, a frame is allocated from the runtime stack

Call Frame function factorial ( n ) { var tmp, k, x; if (n==1) return 1 ; tmp = n * factorial(n-1) ; return tmp; } x value k value local vars tmp value return address 138764225… parameters n value Every time factorial is called, a call frame for that call is added to the run-time stack The call frame is popped off the run-time stack when the call to factorial does a “return”

Call Stack factorial call ret addr tmp n 1 Call Stack factorial call function main ( ) { var K = 4; var res; res = factorial ( K ); alert(res); } function factorial ( n ) { var tmp; if (n==1) return 1 ; tmp = n * factorial(n-1) ; return tmp; ret addr tmp n 2 1 factorial call ret addr tmp n 3 2 factorial call ret addr tmp n 4 6 factorial call res K 4 . . . 24 is pop a call frame off the call stack main call

Call Stack function main ( ) { var K = 4; var res; res = factorial ( K ); alert(res); } function factorial ( n ) { var tmp; if (n==1) return 1 ; tmp = n * factorial(n-1) ; return tmp; ret addr locals… msg “24” alert call res K 4 . . . 24 main call

The Heap The Heap is a “pool” of memory, chunks of which can be dynamically allocated to your program (as it runs) No systematic discipline for allocating/deallocating, such as we do in the run-time stack (LIFO) Very possible for space to be allocated in the heap during a function call, and then still be used in the program when the call stack is gone (after function return) When / how ? TCell tc = new TCell( ); // space for the object comes out of heap // variable “tc” contains pointer to (address of) the // new heap memory chunk

The Heap When / how ? function main ( ) { TCell tcm; tcm = objMaker( ) ; } function objMaker ( ) { TCell tc = new TCell( ); TCell tx = new TCell( ); return tc; TCell sized heap memory methods fields . . . methods fields . . . ret addr tc . . . tx objMaker call objMaker return TCell sized heap memory tcm . . . main call Call stack

The Heap When / how ? function main ( ) { TCell tcm; tcm = objMaker( ) ; } function objMaker ( ) { TCell tc = new TCell( ); TCell tx = new TCell( ); return tc; TCell sized heap memory methods fields . . . No way to access this object, it is now “garbage” methods fields . . . TCell sized heap memory tcm . . . main call Call stack

Program Memory Use stack heap available static allocated class vars, globals, static (writable) code instructions literals (read-only) stack heap available 4th call frame object 3rd call frame object static 2nd call frame main call frame allocated smaller objects

One Physical RAM Space

Stack refs into Heap

Heap Managment Fragmentation C: manual heap management As execution proceeds, object refs are lost methods return, call frames popped off run-time stack, local object vars are gone heap fills with unreachable chunks/objects C: manual heap management malloc gives heap space (in bytes) free must be called to return space to heap Forgetting to call free causes “memory leaks”

Garbage Collection Java: semi-auto heap management stack heap unallocated Java: semi-auto heap management new gives space big enough for object of class no giving it back… garbage collection sweeps up unreachable chunks, consolidates heap into two used and open chunks unreachable stack heap After garbage collection unallocated

Recursion with LIST A LIST can be defined recursively LIST is -- null -- or [ val ]  LIST [ beta ]  [ theta ]  [ alpha ]  [ gamma ] So a function F can process a LIST by dealing with the head item, and then calling the function F recursively , passing in the “rest of” the LIST as a LIST itself. car head cdr rest from LISP

Recursion with LIST Just a note… We did not deal with LIST recursively It’s so easy to do iteratively No worries on blowing out the run time stack TREE is different… code in text is recursive

Recursion with TREE TREE is -- value (root) -- left TREE (child) -- right TREE (child) insert(nVal) { if (nVal==value) return false; if (nVal<value) { if (L!==null) L.insert(nVal) else { // add new node as L } } if (nVal>value) { if (R!==null) R.insert(nVal) else { // add new node as R } } value L, TREE R, TREE ( or TREE is null ) value L, TREE R, TREE

function main ( ) { var x = getUserInput( ); var res = factorial(x); print(res); } function factorial ( n ) { if (n<=1) return 1; return n * factorial(n-1);