Algorithms and Data Structures

Size: px
Start display at page:

Download "Algorithms and Data Structures"

Transcription

1 Recursion Page 1 - Recursion Dr. Fall 2008

2 Recursion Page 2 Outline Introduction Simple Problems Time Complexity and Optimization Advanced Problems

3 Recursion Introduction Page 3 Outline Introduction Simple Problems Time Complexity and Optimization Advanced Problems

4 Recursion Introduction Page 4 Introductory Example Suppose you are responsible for alarming a large group of people in case of an emergency One phone call takes at least 1 minute All phone numbers are publicly known Each individual in the group of size n has a unique identification number i {1,..., n} Your identification number is 1 Everybody is reachable and willing to help How do you organize the alarm most efficiently?

5 Recursion Introduction Page 5 Introductory Example Informal solution: ALARM if the group is empty do nothing else do 1.Divide the group in two parts of equal size (±1) 2.Call a person in the first group a) Inform him/her about the emergency b) Ask him/her to ALARM the rest of the group 3.Call a person in the second group a) Inform him/her about the emergency b) Ask him/her to ALARM the rest of the group

6 Recursion Introduction Page 6 Introductory Example Pseudo-code solution: algorithm alarm(x,y) // x is supposed to alarm x+1 to y print "x is alarmed" if x = y then // no one is left break elseif y x = 1 then // only y is left alarm(y,y) else m (x + y + 1)/2 alarm(x + 1,m) alarm(m + 1,y)

7 Recursion Introduction Page 7 Introductory Example alarm(1,13) 1min. 2min. alarm(3,5) alarm(2,7) alarm(6,7) alarm(9,11) alarm(8,13) 1min. 2min. 1min. 2min. 1min. 2min. 1min. 1min. 2min. alarm(12,13) 1min. max. alarm time alarm(4,4) alarm(5,5) alarm(7,7) alarm(10,10) alarm(11,11) alarm(13,13) Maximal alarm time: t(n) 2( log 2 n 1)min. O(log n) n = 13 t(n) 2 3 = 6min. n = t(n) 2 9 = 18min. n = t(n) 2 19 = 38min.

8 Recursion Introduction Page 8 Recursive Algorithm Recursive Algorithm Algorithm that uses itself as part of the solution Recursive Call A method call in which the method being called is the same as the one making the call Direct Recursion Recursion in which a method directly calls itself Indirect Recursion Recursion in which a chain of two or more method calls returns to the method that originated the chain, e.g. A calls B, B calls C, and C calls A

9 Recursion Introduction Page 9 Example 1: Factorial (Recursion) Compute the factorial of integer n: { 1 n = 1 n! = 1 2 n = n (n 1)! n > 1 algorithm factorial(n) if n = 1 then return 1 // base case of the recursion else return n factorial(n 1) // recursive call

10 Recursion Introduction Page 10 Example 1: Factorial (Recursion) The execution of a recursive algorithm uses a call stack to keep track of previous method call n = 1 factorial(1) Returns 1 n = 2 factorial(2) Returns 2 n = 3 factorial(3) Returns 6 factorial(4) n = 4 Returns 24

11 Recursion Introduction Page 11 Remarks Each recursion must have a base case to stop Each recursive call must reduce the problem size, i.e. leading inescapably to the base case A recursion is called tail-recursive, if the recursive call is always the last executed instruction Each recursive algorithm can be transformed into an iterative algorithm (and vice versa) trivial for tail-recursions easy for so-called augmented recursions not so easy in general (requires a stack to replace the call stack) In a recursive algorithm, the stack is hidden from the user

12 Recursion Introduction Page 12 Example 2: Factorial (Tail-Recursion) The previous factorial algorithm is augmented recursive, i.e. it can be replaced by a tail-recursion algorithm factorial(n) return fact(n,1); algorithm fact(n,result) // auxiliary function if n = 1 then return result; // base case of the recursion else return fact(n 1, n result) // tail recursive call

13 Recursion Introduction Page 13 Example 2: Factorial (Tail-Recursion) n = 1 fact(1,24) Returns 24 fact(2,12) n = 3 n = 2 Returns 24 Tail- Recursion fact(3,4) Returns 24 fact(4,1) n = 4 Returns 24

14 Recursion Introduction Page 14 Example 3: Factorial (Iteration) The tail-recursive factorial algorithm can be replaced by a simple iterative loop algorithm factorial(n) result 1 while n > 0 do result result n n n 1 return result

15 Recursion Introduction Page 15 Recursive vs. Iterative Algorithms Recursive algorithms are often less efficient than their iterative counterparts The overhead of managing the call stack is non-negligible The space complexity is often O(n) or O(log n) instead of O(1) Risk to get "stack overflow" errors Some (functional) programming languages such as Scheme, Lisp, or Haskell detect tail-recursions automatically Nevertheless, recursion has been used to solve some of the biggest and hardest algorithmic problems in computer science!!!

16 Recursion Simple Problems Page 16 Outline Introduction Simple Problems Time Complexity and Optimization Advanced Problems

17 Recursion Simple Problems Page 17 Problem 1: Fibonacci Compute the Fibonacci number 0 if n = 0 F (n) = 1 if n = 1 F (n 1) + F (n 2) if n > 1 Input Integer n 0 Ouput F (n) Examples fibonacci(10) 55 fibonacci(21) 10946

18 Recursion Simple Problems Page 18 Problem 2: Integer Printing Print integers relative to various bases Input Integer n 0, base b 2 Ouput Screen output of [d k d 1 d 0 ] b for n = d k b k + + d 1 b + d 0 Examples printinteger(61, 2) printinteger(61, 16) 3D Auxiliary Function printdigit(d)

19 Recursion Simple Problems Page 19 Problem 3: Palindrome Detect whether a sequence is a palindrome Input Sequence s Ouput true or false Examples palindrome([amanaplanacanalpanama]) true palindrome([recursioniscomplicated]) false Auxiliary Functions size(), first(), last(), removefirst(), removelast()

20 Recursion Simple Problems Page 20 Problem 4: Prefix Determine whether a sequence is the prefix of another sequence Input Sequences s 1 and s 2 Ouput true or false Examples prefix([recursive], [recursivecall]) true prefix([call], [recursivecall]) false Auxiliary Functions isempty(), first(), removefirst()

21 Recursion Simple Problems Page 21 Problem 5: Minimum/Maximum Find both the minimum and the maximum of an sequence of numbers. Input Sequence s of numbers Ouput Pair (min, max) with min = min{s} and max = max{s} Example minmax([6, 1, 2, 3, 12, 4, 3, 8, 0]) ( 4, 12) Auxiliary Functions first(), isempty(), removefirst(), makepair(first, second), firstelt(), secondelt()

22 Recursion Simple Problems Page 22 Problem 6: Line Plotter Plot a line between two points p 1 = (x 1, y 1 ) and p 2 = (x 2, y 2 ) Input Points x 1, y 1, x 2, y 2 Ouput Plot the connecting line on the screen Example plotline(8, 5, 21, 11) see next slide Auxiliary Functions plotpixel(x, y)

23 Recursion Simple Problems Page 23 Problem 6: Line Plotter (cont.) y x

24 Recursion Simple Problems Page 24 Problem 7: Koch Fractal Plot a Koch fractal of maximal depth d between two points d=0 middle d=1 left right d=2

25 Recursion Simple Problems Page 25 Problem 7: Koch Fractal (cont.) Input Integer d, points p 1 = (x 1, y 1 ) and p 2 = (x 2, y 2 ) Ouput Plot the Koch fractal on the screen Example kochfractal(6, p 1, p 2 ) see previous slide Auxiliary Functions plotline(p 1, p 2 ), left(p 1, p 2 ), middle(p 1, p 2 ), right(p 1, p 2 )

26 Recursion Simple Problems Page 26 Problem 8: Towers of Hanoi Move all the blocks from the first to the third tower, one after another, and without ever putting a block on a smaller one Tower 1 Tower 2 Tower 3

27 Recursion Simple Problems Page 27 Problem 8: Towers of Hanoi (cont.) Input Integer n (number of blocks) Ouput Print sequence of instructions on screen Example hanoi(3) 1 3, 1 2, 3 2, 1 3, 2 1, 2 3, 1 3 Auxiliary Functions makestack(), push(e), pop()

28 Recursion Time Complexity and Optimization Page 28 Outline Introduction Simple Problems Time Complexity and Optimization Advanced Problems

29 Recursion Time Complexity and Optimization Page 29 Running Time of Recursions In principle, recursive versions of algorithms can be analyzed like non-recursive algorithms Count primitive operations Express the running time as a function T (n) Classify T (n) using the big-oh notation The problem with recursive algorithms is that T (n) refers to itself Recurrence equation (difficult to solve in general) { 2, for n = 1 Example: T (n) = T (n 1) + 5, for n > 1 for factorial(n), which leads to T (n) = 5(n 1) + 2

30 Recursion Time Complexity and Optimization Page 30 Big-Oh for Recurrence Equations Recurrence equations are often in one of the two following forms: Reducing the problem size by k: (Rules R1 R2) { c if n = d T (n) = q T (n k) + f (n) if n > d Example: c = 2, q = k = d = 1, f (n) = 5 for factorial(n) Dividing the problem size by r: (Rules D1 D4) { c if n = d T (n) = q T (n/r) + f (n) if n > d (see Master-Theorem in [Goodrich et al., 2001], page 268)

31 Recursion Time Complexity and Optimization Page 31 Complexity Rules Overview f (n) O(1) O(log n) O(n) O(n 2 ) R1 q = 1 k 1 n n log n n 2 n 3 R2 q 2 k 1 q n log n q n n q n n 2 qn D1 q = 1 r 2 log n log n n n 2 D2 q 2 r = q n n n log n n 2 D3 q 2 r > q n log r q n log r q n n 2 D4 q 2 r < q n log r q n log r q n log r q n 2

32 Recursion Time Complexity and Optimization Page 32 Memoization A common technique to speed up recursive algorithms is called memoization A memoized function stores (caches) results of previous calls When the function is later called with the same parameters, it returns the stored result rather than recalculating it Memoized functions are not allowed to have side-effects no screen output no global variable assignments no change of object attributes Memoization is usually implemented with hash tables Difficult space/time trade-off

33 Recursion Time Complexity and Optimization Page 33 Memoization: Example fibonacci(5) memoizedfibonacci(5) Complexity is reduced from O(2 n ) to O(n)

34 Recursion Advanced Problems Page 34 Outline Introduction Simple Problems Time Complexity and Optimization Advanced Problems

35 Recursion Advanced Problems Page 35 Problem 9: Flood Fill In a black-and-white bitmap, fill the neighborhood of a given point with black. Consider the bitmap as a 2-dimensional array A[i, j] with A[i, j] {white, black}

36 Recursion Advanced Problems Page 36 Problem 9: Flood Fill (cont.) Input Bitmap A[i, j], integers x, y Ouput Modified bitmap A[i, j] Example floodfill(a, 3, 6) see previous slide Auxiliary Functions arrayxsize(a), arrayysize(a)

37 Recursion Advanced Problems Page 37 Problem 10: Ruler Draw a ruler with n different (sub-) units. Input Integer n Ouput Draw ruler on screen Example ruler(5) Auxiliary Functions drawline(n) draws a line of size n from left to right

38 Recursion Advanced Problems Page 38 Problem 11: Powerset Compute the set of all subsets (= powerset) of a given set Input Set s Ouput Powerset P = 2 s Example powerset({1, 2, 3}) {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}} Auxiliary Functions first(), isempty(), removefirst(), makeset(e), union(s)

39 Recursion Advanced Problems Page 39 Problem 12: Cartesian Product Compute the Cartesian product of a given set of sets Input Sequence s = [s 1 s n ] of sets s i Ouput Cartesian product s 1 s n (a set of sequences) Example product([{1, 2}{a, b}{x, y}]) {[1ax], [1ay],..., [2by]} Auxiliary Functions first(), isempty(), removefirst(), insertfirst(e), makeset(e), union(s)

40 Recursion Advanced Problems Page 40 Problem 13: Permutations Compute the set of all permutations of an ordered set Input Set/sequence s Ouput Set of all permutations of s Example permute([1, 2, 3]) {[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]} Auxiliary Functions first(), isempty(), removefirst(), insertfirst(e), size(), makeset(e), union(s), insertatrank(e, r)

41 Recursion Advanced Problems Page 41 Problem 14: Differentiation Differentiate a mathematical function f (x) according to the following recursive rules: 0 if f (x) = C, C R 1 if f (x) = x f (x) = g (x) ± h (x) if f (x) = g(x) ± h(x) g (x)h(x) + g(x)h (x) if f (x) = g(x)h(x) 0 if f (x) = y, x y g (x)h(x) g(x)h (x) h(x)h(x) N x N 1 for f (x) = g(x) h(x) if f (x) = x N, N Z

42 Recursion Advanced Problems Page 42 Problem 14: Differentiation (cont.) Input f (the function) and v (the variable) Ouput f Examples differentiate( 2x 3 + 3y, x ) 6x 2 differentiate( 2x 2 + 3y, y ) 3 differentiate( 2x 2 + 3y, z ) 0 Auxiliary Functions isconst(), isvar(), issum(), isdiff(), isprod(), isfrac(), ispower(), makesum(f, g), makediff(f, g), makeprod(f, g), makefrac(f, g), makepower(v, n), firstarg(), secondarg(), base(), exp()

What Is Recursion? Recursion. Binary search example postponed to end of lecture

What Is Recursion? Recursion. Binary search example postponed to end of lecture Recursion Binary search example postponed to end of lecture What Is Recursion? Recursive call A method call in which the method being called is the same as the one making the call Direct recursion Recursion

More information

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive. Recursion Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive. Why recursion? o For many problems, the recursion solution is more natural than the alternative

More information

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)! The Tower of Hanoi Recursion Solution recursion recursion recursion Recursive Thinking: ignore everything but the bottom disk. 1 2 Recursive Function Time Complexity Hanoi (n, src, dest, temp): If (n >

More information

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Why? A central concept in Computer Science. Algorithms are ubiquitous. Analysis of Algorithms: A Brief Introduction Why? A central concept in Computer Science. Algorithms are ubiquitous. Using the Internet (sending email, transferring files, use of search engines, online

More information

Recursive Algorithms. Recursion. Motivating Example Factorial Recall the factorial function. { 1 if n = 1 n! = n (n 1)! if n > 1

Recursive Algorithms. Recursion. Motivating Example Factorial Recall the factorial function. { 1 if n = 1 n! = n (n 1)! if n > 1 Recursion Slides by Christopher M Bourke Instructor: Berthe Y Choueiry Fall 007 Computer Science & Engineering 35 Introduction to Discrete Mathematics Sections 71-7 of Rosen cse35@cseunledu Recursive Algorithms

More information

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1 Definition Course: Programming II - Abstract Data Types The ADT Stack The ADT Stack is a linear sequence of an arbitrary number of items, together with access procedures. The access procedures permit insertions

More information

Module 2 Stacks and Queues: Abstract Data Types

Module 2 Stacks and Queues: Abstract Data Types Module 2 Stacks and Queues: Abstract Data Types A stack is one of the most important and useful non-primitive linear data structure in computer science. It is an ordered collection of items into which

More information

PES Institute of Technology-BSC QUESTION BANK

PES Institute of Technology-BSC QUESTION BANK PES Institute of Technology-BSC Faculty: Mrs. R.Bharathi CS35: Data Structures Using C QUESTION BANK UNIT I -BASIC CONCEPTS 1. What is an ADT? Briefly explain the categories that classify the functions

More information

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C Tutorial#1 Q 1:- Explain the terms data, elementary item, entity, primary key, domain, attribute and information? Also give examples in support of your answer? Q 2:- What is a Data Type? Differentiate

More information

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

More information

Section IV.1: Recursive Algorithms and Recursion Trees

Section IV.1: Recursive Algorithms and Recursion Trees Section IV.1: Recursive Algorithms and Recursion Trees Definition IV.1.1: A recursive algorithm is an algorithm that solves a problem by (1) reducing it to an instance of the same problem with smaller

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

Sequential Data Structures

Sequential Data Structures Sequential Data Structures In this lecture we introduce the basic data structures for storing sequences of objects. These data structures are based on arrays and linked lists, which you met in first year

More information

10CS35: Data Structures Using C

10CS35: Data Structures Using C CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a

More information

Chapter 8: Bags and Sets

Chapter 8: Bags and Sets Chapter 8: Bags and Sets In the stack and the queue abstractions, the order that elements are placed into the container is important, because the order elements are removed is related to the order in which

More information

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2 Stacks Outline The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack Stacks 2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure

More information

Data Structures. Algorithm Performance and Big O Analysis

Data Structures. Algorithm Performance and Big O Analysis Data Structures Algorithm Performance and Big O Analysis What s an Algorithm? a clearly specified set of instructions to be followed to solve a problem. In essence: A computer program. In detail: Defined

More information

Data Structure with C

Data Structure with C Subject: Data Structure with C Topic : Tree Tree A tree is a set of nodes that either:is empty or has a designated node, called the root, from which hierarchically descend zero or more subtrees, which

More information

3.5 RECURSIVE ALGORITHMS

3.5 RECURSIVE ALGORITHMS Section 3.5 Recursive Algorithms 3.5.1 3.5 RECURSIVE ALGORITHMS review : An algorithm is a computational representation of a function. Remark: Although it is often easier to write a correct recursive algorithm

More information

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution 16. Recursion COMP 110 Prasun Dewan 1 Loops are one mechanism for making a program execute a statement a variable number of times. Recursion offers an alternative mechanism, considered by many to be more

More information

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010 Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010 Problem 1. In each of the following question, please specify if the statement

More information

Algorithms and Data Structures

Algorithms and Data Structures Algorithms and Data Structures Part 2: Data Structures PD Dr. rer. nat. habil. Ralf-Peter Mundani Computation in Engineering (CiE) Summer Term 2016 Overview general linked lists stacks queues trees 2 2

More information

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++ Brad Rippe CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++ Recursion Recursion CHAPTER 14 Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively

More information

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara CMPSC 24: Lecture 13 Recursion Divyakant Agrawal Department of Computer Science UC Santa Barbara 5/12/10 1 Lecture Plan Recursion General structure of recursive soluions Why do recursive soluions terminate?

More information

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge, The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge, cheapest first, we had to determine whether its two endpoints

More information

DATA STRUCTURES USING C

DATA STRUCTURES USING C DATA STRUCTURES USING C QUESTION BANK UNIT I 1. Define data. 2. Define Entity. 3. Define information. 4. Define Array. 5. Define data structure. 6. Give any two applications of data structures. 7. Give

More information

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and: Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)

More information

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push) -----------------------------------------

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push) ----------------------------------------- =============================================================================================================================== DATA STRUCTURE PSEUDO-CODE EXAMPLES (c) Mubashir N. Mir - www.mubashirnabi.com

More information

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms. COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms 1 Activation Records activation declaration location Recall that an activation

More information

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015 CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis Linda Shapiro Today Registration should be done. Homework 1 due 11:59 pm next Wednesday, January 14 Review math essential

More information

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction Class Overview CSE 326: Data Structures Introduction Introduction to many of the basic data structures used in computer software Understand the data structures Analyze the algorithms that use them Know

More information

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. 1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. base address 2. The memory address of fifth element of an array can be calculated

More information

Recursion vs. Iteration Eliminating Recursion

Recursion vs. Iteration Eliminating Recursion Recursion vs. Iteration Eliminating Recursion continued CS 311 Data Structures and Algorithms Lecture Slides Monday, February 16, 2009 Glenn G. Chappell Department of Computer Science University of Alaska

More information

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types EECS 281: Data Structures and Algorithms The Foundation: Data Structures and Abstract Data Types Computer science is the science of abstraction. Abstract Data Type Abstraction of a data structure on that

More information

STACKS,QUEUES, AND LINKED LISTS

STACKS,QUEUES, AND LINKED LISTS STACKS,QUEUES, AND LINKED LISTS Stacks Queues Linked Lists Double-Ended Queues Case Study: A Stock Analysis Applet 1 Stacks Astack is a container of objects that are inserted and removed according to the

More information

Analysis of a Search Algorithm

Analysis of a Search Algorithm CSE 326 Lecture 4: Lists and Stacks 1. Agfgd 2. Dgsdsfd 3. Hdffdsf 4. Sdfgsfdg 5. Tefsdgass We will review: Analysis: Searching a sorted array (from last time) List ADT: Insert, Delete, Find, First, Kth,

More information

PROBLEMS (Cap. 4 - Istruzioni macchina)

PROBLEMS (Cap. 4 - Istruzioni macchina) 98 CHAPTER 2 MACHINE INSTRUCTIONS AND PROGRAMS PROBLEMS (Cap. 4 - Istruzioni macchina) 2.1 Represent the decimal values 5, 2, 14, 10, 26, 19, 51, and 43, as signed, 7-bit numbers in the following binary

More information

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., 2001. 1995-2001 Barnette ND, McQuain WD

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., 2001. 1995-2001 Barnette ND, McQuain WD 1 Slides 1. Table of Contents 2. Definitions 3. Simple 4. Recursive Execution Trace 5. Attributes 6. Recursive Array Summation 7. Recursive Array Summation Trace 8. Coding Recursively 9. Recursive Design

More information

Chapter 15 Functional Programming Languages

Chapter 15 Functional Programming Languages Chapter 15 Functional Programming Languages Introduction - The design of the imperative languages is based directly on the von Neumann architecture Efficiency (at least at first) is the primary concern,

More information

The Set Data Model CHAPTER 7. 7.1 What This Chapter Is About

The Set Data Model CHAPTER 7. 7.1 What This Chapter Is About CHAPTER 7 The Set Data Model The set is the most fundamental data model of mathematics. Every concept in mathematics, from trees to real numbers, is expressible as a special kind of set. In this book,

More information

Introduction. Earlier programs structured as methods that call one another in a disciplined, hierarchical manner Recursive methods

Introduction. Earlier programs structured as methods that call one another in a disciplined, hierarchical manner Recursive methods Recursion 1 2 Introduction Earlier programs structured as methods that call one another in a disciplined, hierarchical manner Recursive methods Call themselves Useful for some problems to define a method

More information

Regular Expressions and Automata using Haskell

Regular Expressions and Automata using Haskell Regular Expressions and Automata using Haskell Simon Thompson Computing Laboratory University of Kent at Canterbury January 2000 Contents 1 Introduction 2 2 Regular Expressions 2 3 Matching regular expressions

More information

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16 Queues and Stacks Atul Prakash Downey: Chapter 15 and 16 Queues Queues occur in real life a lot. Queues at checkout Queues in banks In software systems: Queue of requests at a web servers Properties of

More information

csci 210: Data Structures Recursion

csci 210: Data Structures Recursion csci 210: Data Structures Recursion Summary Topics recursion overview simple examples Sierpinski gasket Hanoi towers Blob check READING: GT textbook chapter 3.5 Recursion In general, a method of defining

More information

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues 1. 2004 Goodrich, Tamassia

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues 1. 2004 Goodrich, Tamassia This lecture Abstract data types Stacks Queues ADTs, Stacks, Queues 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations

More information

Algorithms are the threads that tie together most of the subfields of computer science.

Algorithms are the threads that tie together most of the subfields of computer science. Algorithms Algorithms 1 Algorithms are the threads that tie together most of the subfields of computer science. Something magically beautiful happens when a sequence of commands and decisions is able to

More information

Symbol Tables. Introduction

Symbol Tables. Introduction Symbol Tables Introduction A compiler needs to collect and use information about the names appearing in the source program. This information is entered into a data structure called a symbol table. The

More information

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * * Binary Heaps A binary heap is another data structure. It implements a priority queue. Priority Queue has the following operations: isempty add (with priority) remove (highest priority) peek (at highest

More information

Chapter 3. if 2 a i then location: = i. Page 40

Chapter 3. if 2 a i then location: = i. Page 40 Chapter 3 1. Describe an algorithm that takes a list of n integers a 1,a 2,,a n and finds the number of integers each greater than five in the list. Ans: procedure greaterthanfive(a 1,,a n : integers)

More information

Mathematics for Computer Science/Software Engineering. Notes for the course MSM1F3 Dr. R. A. Wilson

Mathematics for Computer Science/Software Engineering. Notes for the course MSM1F3 Dr. R. A. Wilson Mathematics for Computer Science/Software Engineering Notes for the course MSM1F3 Dr. R. A. Wilson October 1996 Chapter 1 Logic Lecture no. 1. We introduce the concept of a proposition, which is a statement

More information

Warshall s Algorithm: Transitive Closure

Warshall s Algorithm: Transitive Closure CS 0 Theory of Algorithms / CS 68 Algorithms in Bioinformaticsi Dynamic Programming Part II. Warshall s Algorithm: Transitive Closure Computes the transitive closure of a relation (Alternatively: all paths

More information

Figure 1: Graphical example of a mergesort 1.

Figure 1: Graphical example of a mergesort 1. CSE 30321 Computer Architecture I Fall 2011 Lab 02: Procedure Calls in MIPS Assembly Programming and Performance Total Points: 100 points due to its complexity, this lab will weight more heavily in your

More information

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012 Binary numbers The reason humans represent numbers using decimal (the ten digits from 0,1,... 9) is that we have ten fingers. There is no other reason than that. There is nothing special otherwise about

More information

Dynamic Programming. Lecture 11. 11.1 Overview. 11.2 Introduction

Dynamic Programming. Lecture 11. 11.1 Overview. 11.2 Introduction Lecture 11 Dynamic Programming 11.1 Overview Dynamic Programming is a powerful technique that allows one to solve many different types of problems in time O(n 2 ) or O(n 3 ) for which a naive approach

More information

Loop Invariants and Binary Search

Loop Invariants and Binary Search Loop Invariants and Binary Search Chapter 4.3.3 and 9.3.1-1 - Outline Ø Iterative Algorithms, Assertions and Proofs of Correctness Ø Binary Search: A Case Study - 2 - Outline Ø Iterative Algorithms, Assertions

More information

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013 Exercises Software Development I 11 Recursion, Binary (Search) Trees Towers of Hanoi // Tree Traversal January 16, 2013 Software Development I Winter term 2012/2013 Institute for Pervasive Computing Johannes

More information

Solutions to Homework 6

Solutions to Homework 6 Solutions to Homework 6 Debasish Das EECS Department, Northwestern University ddas@northwestern.edu 1 Problem 5.24 We want to find light spanning trees with certain special properties. Given is one example

More information

IV.2 (b) Higher level programming concepts for URMs Anton Setzer

IV.2 (b) Higher level programming concepts for URMs Anton Setzer CS 275 Automata and Formal Language Theory Course Notes Additional Material Part IV: Limits of Computation Chapt. IV.2: The URM IV.2 (a) Definition of the URM IV.2 (b) Higher level programming concepts

More information

Mathematical Induction

Mathematical Induction Mathematical Induction (Handout March 8, 01) The Principle of Mathematical Induction provides a means to prove infinitely many statements all at once The principle is logical rather than strictly mathematical,

More information

Solving Problems Recursively

Solving Problems Recursively Solving Problems Recursively Recursion is an indispensable tool in a programmer s toolkit Allows many complex problems to be solved simply Elegance and understanding in code often leads to better programs:

More information

Dynamic Programming Problem Set Partial Solution CMPSC 465

Dynamic Programming Problem Set Partial Solution CMPSC 465 Dynamic Programming Problem Set Partial Solution CMPSC 465 I ve annotated this document with partial solutions to problems written more like a test solution. (I remind you again, though, that a formal

More information

Linear Programming for Optimization. Mark A. Schulze, Ph.D. Perceptive Scientific Instruments, Inc.

Linear Programming for Optimization. Mark A. Schulze, Ph.D. Perceptive Scientific Instruments, Inc. 1. Introduction Linear Programming for Optimization Mark A. Schulze, Ph.D. Perceptive Scientific Instruments, Inc. 1.1 Definition Linear programming is the name of a branch of applied mathematics that

More information

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2) Sorting revisited How did we use a binary search tree to sort an array of elements? Tree Sort Algorithm Given: An array of elements to sort 1. Build a binary search tree out of the elements 2. Traverse

More information

6. Standard Algorithms

6. Standard Algorithms 6. Standard Algorithms The algorithms we will examine perform Searching and Sorting. 6.1 Searching Algorithms Two algorithms will be studied. These are: 6.1.1. inear Search The inear Search The Binary

More information

Examples of Functions

Examples of Functions Examples of Functions In this document is provided examples of a variety of functions. The purpose is to convince the beginning student that functions are something quite different than polynomial equations.

More information

Scheduling Shop Scheduling. Tim Nieberg

Scheduling Shop Scheduling. Tim Nieberg Scheduling Shop Scheduling Tim Nieberg Shop models: General Introduction Remark: Consider non preemptive problems with regular objectives Notation Shop Problems: m machines, n jobs 1,..., n operations

More information

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1 Stacks (and Queues) 1 Stacks Stack: what is it? ADT Applications Implementation(s) 2 CSCU9A3 1 Stacks and ueues A stack is a very important data structure in computing science. A stack is a seuence of

More information

Curriculum Map. Discipline: Computer Science Course: C++

Curriculum Map. Discipline: Computer Science Course: C++ Curriculum Map Discipline: Computer Science Course: C++ August/September: How can computer programs make problem solving easier and more efficient? In what order does a computer execute the lines of code

More information

Data Structures and Algorithms V22.0102. Otávio Braga

Data Structures and Algorithms V22.0102. Otávio Braga Data Structures and Algorithms V22.0102 Otávio Braga We use a stack When an operand is read, output it When an operator is read Pop until the top of the stack has an element of lower precedence Then push

More information

Introduction to Data Structures

Introduction to Data Structures Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate

More information

Collatz Sequence. Fibbonacci Sequence. n is even; Recurrence Relation: a n+1 = a n + a n 1.

Collatz Sequence. Fibbonacci Sequence. n is even; Recurrence Relation: a n+1 = a n + a n 1. Fibonacci Roulette In this game you will be constructing a recurrence relation, that is, a sequence of numbers where you find the next number by looking at the previous numbers in the sequence. Your job

More information

Algorithms. Margaret M. Fleck. 18 October 2010

Algorithms. Margaret M. Fleck. 18 October 2010 Algorithms Margaret M. Fleck 18 October 2010 These notes cover how to analyze the running time of algorithms (sections 3.1, 3.3, 4.4, and 7.1 of Rosen). 1 Introduction The main reason for studying big-o

More information

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio. Organization of Programming Languages CS320/520N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Names, Bindings, and Scopes A name is a symbolic identifier used

More information

Data Structures in the Java API

Data Structures in the Java API Data Structures in the Java API Vector From the java.util package. Vectors can resize themselves dynamically. Inserting elements into a Vector whose current size is less than its capacity is a relatively

More information

Party Time! Computer Science I. Signature Examples PAIR OBJ. The Signature of a Procedure. Building a Set. Testing for Membership in a Set

Party Time! Computer Science I. Signature Examples PAIR OBJ. The Signature of a Procedure. Building a Set. Testing for Membership in a Set Computer Science I Professor Tom Ellman Lecture 21 Party Time! Whom shall you invite? We will write the Party Planner program. It will select SETS of guests. By reasoning with RELATIONS. Before we party,

More information

Analysis of Binary Search algorithm and Selection Sort algorithm

Analysis of Binary Search algorithm and Selection Sort algorithm Analysis of Binary Search algorithm and Selection Sort algorithm In this section we shall take up two representative problems in computer science, work out the algorithms based on the best strategy to

More information

INTRODUCTORY SET THEORY

INTRODUCTORY SET THEORY M.Sc. program in mathematics INTRODUCTORY SET THEORY Katalin Károlyi Department of Applied Analysis, Eötvös Loránd University H-1088 Budapest, Múzeum krt. 6-8. CONTENTS 1. SETS Set, equal sets, subset,

More information

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; } Functions Recursion C++ functions Declare/prototype int myfunction (int ); Define int myfunction (int x){ int y = x*x; return y; Call int a; a = myfunction (7); function call flow types type of function

More information

Sample Questions Csci 1112 A. Bellaachia

Sample Questions Csci 1112 A. Bellaachia Sample Questions Csci 1112 A. Bellaachia Important Series : o S( N) 1 2 N N i N(1 N) / 2 i 1 o Sum of squares: N 2 N( N 1)(2N 1) N i for large N i 1 6 o Sum of exponents: N k 1 k N i for large N and k

More information

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structures Using C++ 2E. Chapter 5 Linked Lists Data Structures Using C++ 2E Chapter 5 Linked Lists Doubly Linked Lists Traversed in either direction Typical operations Initialize the list Destroy the list Determine if list empty Search list for a given

More information

Query Processing C H A P T E R12. Practice Exercises

Query Processing C H A P T E R12. Practice Exercises C H A P T E R12 Query Processing Practice Exercises 12.1 Assume (for simplicity in this exercise) that only one tuple fits in a block and memory holds at most 3 blocks. Show the runs created on each pass

More information

Lecture Notes on Linear Search

Lecture Notes on Linear Search Lecture Notes on Linear Search 15-122: Principles of Imperative Computation Frank Pfenning Lecture 5 January 29, 2013 1 Introduction One of the fundamental and recurring problems in computer science is

More information

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser) High-Level Programming Languages Nell Dale & John Lewis (adaptation by Michael Goldwasser) Low-Level Languages What are disadvantages of low-level languages? (e.g., machine code or assembly code) Programming

More information

MapReduce and Distributed Data Analysis. Sergei Vassilvitskii Google Research

MapReduce and Distributed Data Analysis. Sergei Vassilvitskii Google Research MapReduce and Distributed Data Analysis Google Research 1 Dealing With Massive Data 2 2 Dealing With Massive Data Polynomial Memory Sublinear RAM Sketches External Memory Property Testing 3 3 Dealing With

More information

Mathematics for Algorithm and System Analysis

Mathematics for Algorithm and System Analysis Mathematics for Algorithm and System Analysis for students of computer and computational science Edward A. Bender S. Gill Williamson c Edward A. Bender & S. Gill Williamson 2005. All rights reserved. Preface

More information

(IALC, Chapters 8 and 9) Introduction to Turing s life, Turing machines, universal machines, unsolvable problems.

(IALC, Chapters 8 and 9) Introduction to Turing s life, Turing machines, universal machines, unsolvable problems. 3130CIT: Theory of Computation Turing machines and undecidability (IALC, Chapters 8 and 9) Introduction to Turing s life, Turing machines, universal machines, unsolvable problems. An undecidable problem

More information

8 Divisibility and prime numbers

8 Divisibility and prime numbers 8 Divisibility and prime numbers 8.1 Divisibility In this short section we extend the concept of a multiple from the natural numbers to the integers. We also summarize several other terms that express

More information

Unordered Linked Lists

Unordered Linked Lists Unordered Linked Lists Derive class unorderedlinkedlist from the abstract class linkedlisttype Implement the operations search, insertfirst, insertlast, deletenode See code on page 292 Defines an unordered

More information

Ensemble Methods. Knowledge Discovery and Data Mining 2 (VU) (707.004) Roman Kern. KTI, TU Graz 2015-03-05

Ensemble Methods. Knowledge Discovery and Data Mining 2 (VU) (707.004) Roman Kern. KTI, TU Graz 2015-03-05 Ensemble Methods Knowledge Discovery and Data Mining 2 (VU) (707004) Roman Kern KTI, TU Graz 2015-03-05 Roman Kern (KTI, TU Graz) Ensemble Methods 2015-03-05 1 / 38 Outline 1 Introduction 2 Classification

More information

CS473 - Algorithms I

CS473 - Algorithms I CS473 - Algorithms I Lecture 9 Sorting in Linear Time View in slide-show mode 1 How Fast Can We Sort? The algorithms we have seen so far: Based on comparison of elements We only care about the relative

More information

Common Data Structures

Common Data Structures Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees

More information

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic Queues Outline and Required Reading: Queues ( 4. except 4..4) COSC, Fall 3, Section A Instructor: N. Vlajic Queue ADT Queue linear data structure organized according to first-in/first-out (FIFO) principle!

More information

Sample Induction Proofs

Sample Induction Proofs Math 3 Worksheet: Induction Proofs III, Sample Proofs A.J. Hildebrand Sample Induction Proofs Below are model solutions to some of the practice problems on the induction worksheets. The solutions given

More information

Chapter 13: Query Processing. Basic Steps in Query Processing

Chapter 13: Query Processing. Basic Steps in Query Processing Chapter 13: Query Processing! Overview! Measures of Query Cost! Selection Operation! Sorting! Join Operation! Other Operations! Evaluation of Expressions 13.1 Basic Steps in Query Processing 1. Parsing

More information

Chapter 3. Distribution Problems. 3.1 The idea of a distribution. 3.1.1 The twenty-fold way

Chapter 3. Distribution Problems. 3.1 The idea of a distribution. 3.1.1 The twenty-fold way Chapter 3 Distribution Problems 3.1 The idea of a distribution Many of the problems we solved in Chapter 1 may be thought of as problems of distributing objects (such as pieces of fruit or ping-pong balls)

More information

Stacks. Linear data structures

Stacks. Linear data structures Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations

More information

24. The Branch and Bound Method

24. The Branch and Bound Method 24. The Branch and Bound Method It has serious practical consequences if it is known that a combinatorial problem is NP-complete. Then one can conclude according to the present state of science that no

More information

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Questions 1 through 25 are worth 2 points each. Choose one best answer for each. Questions 1 through 25 are worth 2 points each. Choose one best answer for each. 1. For the singly linked list implementation of the queue, where are the enqueues and dequeues performed? c a. Enqueue in

More information

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees

Learning Outcomes. COMP202 Complexity of Algorithms. Binary Search Trees and Other Search Trees Learning Outcomes COMP202 Complexity of Algorithms Binary Search Trees and Other Search Trees [See relevant sections in chapters 2 and 3 in Goodrich and Tamassia.] At the conclusion of this set of lecture

More information