Advanced Higher Computing Science

Slides:



Advertisements
Similar presentations
MATH 224 – Discrete Mathematics
Advertisements

DIVIDE AND CONQUER APPROACH. General Method Works on the approach of dividing a given problem into smaller sub problems (ideally of same size).  Divide.
Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Data Structures Review Session 1
1 Chapter 7 Recursion. 2 What Is Recursion? l Recursive call A method call in which the method being called is the same as the one making the call l Direct.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Sorting HKOI Training Team (Advanced)
Chapter 12 Recursion, Complexity, and Searching and Sorting
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
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.
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.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
CSC 211 Data Structures Lecture 13
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Data Structure Introduction.
1 Section 2.1 Algorithms. 2 Algorithm A finite set of precise instructions for performing a computation or for solving a problem.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
Recursion in Java The answer to life’s greatest mysteries are on the last slide.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
INTRO2CS Tirgul 8 1. Searching and Sorting  Tips for debugging  Binary search  Sorting algorithms:  Bogo sort  Bubble sort  Quick sort and maybe.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Advanced Higher Computing Science Standard Algorithms
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 19: Recursion.
Chapter 15 Recursion.
Recursion DRILL: Please take out your notes on Recursion
Data Structures I (CPCS-204)
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Recursion A problem solving technique where an algorithm is defined in terms of itself A recursive method is a method that calls itself A recursive algorithm.
Analysis of Algorithms
Decrease-and-Conquer Approach
Chapter 15 Recursion.
Chapter 9: Searching, Sorting, and Algorithm Analysis
CS1371 Introduction to Computing for Engineers
Algorithm Analysis CSE 2011 Winter September 2018.
Chapter 8: Recursion Java Software Solutions
Teach A level Computing: Algorithms and Data Structures
Programming with Recursion
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
CS 3343: Analysis of Algorithms
Recursion Chapter 11.
Algorithm An algorithm is a finite set of steps required to solve a problem. An algorithm must have following properties: Input: An algorithm must have.
Unit-2 Divide and Conquer
Chapter 8: Recursion Java Software Solutions
Winter 2018 CISC101 12/2/2018 CISC101 Reminders
Data Structures Review Session
Data Structures (CS212D) Week # 2: Arrays.
Chapter 4.
Basics of Recursion Programming with Recursion
Chapter 11 Recursion.
Arrays Week 2.
Chapter 8: Recursion Java Software Solutions
11 Recursion Software Solutions Lewis & Loftus java 5TH EDITION
Recursion Chapter 11.
Chapter 18 Recursion.
Last Class We Covered Recursion Stacks Parts of a recursive function:
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Java Software Solutions Foundations of Program Design Sixth Edition
Presentation transcript:

Advanced Higher Computing Science Recursion

In this session we will look at the difference between iterative and recursive solutions to programming problems and what characterizes a recursive solution

Learning content What is recursion? Recursion pros and cons Comparing iterative versus recursive solutions The stopping condition in recursion Recursive binary search Recursive quick sort Fractal graphics Recursion in Prolog Project: Must include a minimum of two from: standard algorithms (binary search, sorts, recursion) data structures (linked list, queues, stacks) data processing (SQL) web development (HTML forms, scripting)

Definition of recursion Recursion: See Recursion A common "joke" in computing textbook indexes.

are where a procedure or function calls itself Recursive programs: are where a procedure or function calls itself always need a "base case" or stopping condition A more helpful definition

Recursion pros and cons Recursion is a powerful programming technique, and is efficient in that it often reduces the amount of code required Recursive code can be very memory intensive because sub procedure calls are all held in memory until the base condition is met Recursion can lead to an infinite loop if not terminated correctly Powerful but also dangerous

Descending Stars (iterative) PROCEDURE descendingStars (INTEGER value) FOR outer FROM value TO 1 STEP -1 DO FOR inner FROM 1 TO outer DO SEND "*" TO DISPLAY END FOR SEND "\n" TO DISPLAY END PROCEDURE Task from National 4 usually used to get people to think about nested loops. In this example the procedure has been called with the value 5 as its parameter

Descending Stars (recursive) PROCEDURE recursiveStars (INTEGER value) DECLARE newValue INITIALLY 0 IF value > 0 THEN FOR counter FROM 1 TO value DO SEND "*" TO DISPLAY END FOR SEND "\n" TO DISPLAY SET newValue TO value – 1 recursiveStars (newValue) END IF END PROCEDURE This is the recursive version of the same program. Note that the inner loop is replaced by a recursive call recursiveStars (newValue) recursiveStars is called with the actual parameter newValue (might be better if I had used Set here rather than DECLARE Again in this instance the procedure has been called with the value 5 as its parameter

Descending Stars (recursive) If the value is zero then stop Otherwise call the recursiveStars procedure with one less than value Note that the variable newValue is local to the stars procedure, so every time recursiveStars is called, it is called with newValue as an actual parameter.

Descending Stars (recursive) PROCEDURE recursiveStars (INTEGER value) IF value > 0 THEN FOR counter FROM 1 TO value DO SEND "*" TO DISPLAY END FOR SEND "\n" TO DISPLAY DECLARE newValue INITIALLY value – 1 recursiveStars (newValue) END IF END PROCEDURE Stopping condition There will always be one or more base cases or stopping conditions in a recursive sub program

Sum of numbers from 1 to n FUNCTION sumNums (INTEGER number) RETURNS INTEGER IF number = 1 THEN RETURN number ELSE RETURN sumNums (number-1) + number END IF END FUNCTION

the sum of all numbers between 0 and 1 is 1 Sum of numbers from 1 to n the sum of all numbers between 0 and 1 is 1 the sum of all numbers between that number and 1, is that number plus the sum of all numbers between it and that number -1 The sumnums of n = n + sumnums of (n-1)

Sum of numbers from 1 to n FUNCTION sumNums (INTEGER number) RETURNS INTEGER IF number = 1 THEN RETURN number ELSE RETURN sumNums (number-1) + number END IF END FUNCTION Stopping condition

Factorial of n (n!) FUNCTION factorial (INTEGER number) RETURNS INTEGER IF number = 1 THEN RETURN number ELSE RETURN factorial (number-1) * number END IF END FUNCTION Factorial is a function important in probability calculations The number of possible permutations of n items is n! (gets very large very quickly)

The factorial of any number n is n times the factorial of (n-1) Factorial of n (n!) The factorial of 1 is 1 The factorial of any number n is n times the factorial of (n-1)

Factorial of n (n!) FUNCTION factorial (INTEGER number) RETURNS INTEGER IF number = 1 THEN RETURN number ELSE RETURN factorial (number-1) * number END IF END FUNCTION Stopping condition

Recursive Binary search IF <the middle item in the array = the search key> THEN <search key has been found> ELSE IF <middle item in the array < the search key> THEN <binarySearch the lower half of the array> IF <middle item in the array > the search key> THEN <binarySearch the upper half of the array> END IF When the binary search is considered as a recursive program, it looks a lot easier to understand.

Recursive Binary search FUNCTION binarySearch (ARRAY OF INTEGER myArray, INTEGER left, INTEGER right, INTEGER valueToFind) RETURNS INTEGER DECLARE middle INITIALLY (left+right)/2 IF myArray[middle]= valueToFind THEN RETURN middle ELSE IF myArray[middle] < value THEN RETURN binarySearch(myArray, left, middle, valueToFind) RETURN binarySearch(myArray, middle+1, right, valueToFind) END IF END FUNCTION

Recursive Quicksort (ascending order) PROCEDURE quickSort(ARRAY OF INTEGER list, INTEGER left, INTEGER right)   DECLARE pivotPosition AS INTEGER INITIALLY 0 IF left < right THEN SET pivotPosition TO partition(list, left, right) quickSort(list, left, pivotPositon) quickSort(list, pivotPositon + 1, right) END IF END PROCEDURE FUNCTION partition (ARRAY OF INTEGER list, INTEGER left, INTEGER right) RETURNS INTEGER <swaps the items in the list and returns a new pivot position> END FUNCTION Another divide and conquer recursive algorithm

Fractal Graphics: the Koch snowflake PROCEDURE side (REAL length, INTEGER iterations) IF (iterations = 0 THEN penMove (length) ELSE side (length, iterations -1) penRotate (-60) penRotate (120) side (length , iterations- 1 ) END IF END PROCEDURE Fractal graphics make a lot of use of recursion, because of course a fractal is just an infinitely repeated formula. Fractals frequently feature in nature, although randomness is also part of the equation. Coastlines can be considered to be one of natures fractals. Zoom in on any coastline and it will still look like a coastline until you get down to the molecular level. side (40, 1)

Fractal Graphics: the Koch snowflake PROCEDURE recursiveSide (REAL length, INTEGER iterations) IF (iterations = 0) THEN penMove (length) ELSE recursiveSide (length, iterations -1) penRotate (-60) penRotate (120) recursiveSide (length, iterations- 1 ) END IF END PROCEDURE side, (10 3)

Fractal Graphics : the Koch snowflake PROCEDURE kochFractal (REAL length, INTEGER iterations) penDown() penHome() FOR counter FROM 1 TO 3 DO penRotate (120) recursiveSide(length,iterations) END FOR END PROCEDURE kochFractal (10, 3)

Integer to Binary string FUNCTION binaryString (INTEGER number) RETURNS STRING DECLARE newDigit INITIALLY 0 DECLARE smallerNumber INITIALLY 0 DECLARE newString INITIALLY "" IF number = 1 THEN RETURN "1" ELSE SET newDigit TO asciiValue (number MOD 2) SET smallerNumber TO number \ 2 #integer division SET newString TO binaryString (smallerNumber) RETURN newString & newDigit END IF END FUNCTION FUNCTION asciiValue (INTEGER number) RETURNS STRING <convert single digit to ASCII value of number to newString > RETURN newString This is an example in the Scholar notes. The asciValue function will often be a standard one which comes with the programming language. CHR$ in basic, CHR in Python

Prolog: Programming in Logic Prolog is a declarative language Prolog programs often make use of recursive techniques. Prolog programs consist of a set of facts and rules. These facts and rules together make up the knowledge base. When a program is run, the compiler (often referred to as the inference engine) will match the inputs to the program with these facts and rules to work out their logical consequence. If you did the AI topic in the old Higher then you will be familiar with prolog

Prolog: Sum of numbers sumnums(1,1). sumnums(Number,Sum):- Newnumber is Number - 1, sumnums(Newnumber, Smallersum), Sum is Smallernumber + Number. Fact: The sumnums of 1 is 1 Rule: The sumnums of any other number is that number plus the sumnums of one less than that number

Prolog: Factorial factorial(1,1). factorial(Num,Answer):- Nextnum is Num - 1, factorial(Nextnum,Nearly_answer), Answer is Num * Nearly_answer. Fact: The factorial of 1 is 1 Rule: The factorial of any other number is that number times the factorial of one less than that number

Prolog: Total of a list total([],0). total([Head|Tail],Answer):- total(Tail,Tail_total), Answer is Head + Tail_total. Fact: The total of an empty list is zero Rule: The total of any other list is the head plus the total of the tail

Prolog: member of a list member_of(Item,[Item|Tail]). member_of(Item,[Head|Tail]):- member_of(Item,Tail). Fact: An item at the head of a list is in that list Rule: An item is in a list if it is in the tail of that list

Prolog: member of a list Query Rule Fact ?- yes answer

Prolog: linear search (list) pos_of_item(Item,[Item|Tail],1).   pos_of_item(Item,[Head|Tail],Pos):- pos_of_item(Item,Tail,Newpos), Pos is Newpos + 1. In the case of the item not being present in the list the prolog inference engine would return "no" Fact: The item at the head of a list is in position 1 Rule: The position of any other item is one more than its position in the tail of the list

List Processing: descending values A list record is defined recursively as a head (the first item in the list) , followed by the rest of the list (its tail). RECORD List IS {INTEGER head, List tail} FUNCTION integers (INTEGER n) RETURNS List IF n = 0 THEN RETURN {} ELSE RETURN {n, integers(n-1)} END IF END FUNCTION This recursive function will return an ordered list of integers from n down to 1. It uses the fact that a list with nothing in it is an empty list {}, and the rule that any other list will be made up of n followed by a tail which is a made up of a list of numbers from n-1 down. A list can be defined recursively as a record

List Processing: Insert a value RECORD List IS {INTEGER head, List tail} FUNCTION insert (INTEGER n, List myList) RETURNS List IF myList = {} THEN RETURN {n,{}} END IF IF n > myList.head THEN RETURN {n, myList} ELSE RETURN {myList.head, insert (n, myList.tail)} END FUNCTION This recursive insert function inserts an integer n into a list newList. It uses the fact that inserting an integer into an empty list creates a new list made up of n followed by an empty list, and the fact that inserting an integer n which is greater than the head of the list creates a new list made up of n followed by that list. The rule is that inserting any other integer results in a new list consisting of the head of the list followed by the result of inserting n into the tail of the list.

List Processing: Insert a value If the following code segment was executed, what would the contents of newsList1 and newList2 be? SET myList TO integers(4) SET newList1 TO insert (7, myList) SET newList2 TO insert (3, newList1) newList1 = {7,4,3,2,1} newList2 = {7,4,3,3, 2,1}

List processing: Linear search RECORD List IS {INTEGER head, List tail} FUNCTION linearSearch (INTEGER target, List numbers) RETURNS INTEGER IF numbers = {} THEN RETURN -1 END IF IF target = numbers.head THEN RETURN 1 ELSE RETURN linearSearch (target, numbers.tail) + 1 END FUNCTION This algorithm is almost identical to the prolog program we saw earlier Fact: The empty list contains no items Fact: The item at the head of a list is in position 1 Rule: The position of any other item is one more than its position in the tail of the list

Summary Recursion is a powerful programming technique which often results in more elegant and readable code Many problems can be more easily solved using recursion rather than iteration Recursive code can be very memory intensive because sub procedure calls are all held in memory until the base condition is met

Thank you. Please take a minute to give your evaluation for today's session at http://svy.mk/2mYMvnr