SlideShare a Scribd company logo
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
And More
Recursion
And More Recursion page 2
© Dr. Jonathan (Yahya) Cazalas
Binary Search – A reminder
 Array Search
 We are given the following sorted array:
 We are searching for the value, 19 (for example)
 Remember, we said that you search the middle
element
 If found, you are done
 If the element in the middle is greater than 19
 Search to the LEFT (cuz 19 MUST be to the left)
 If the element in the middle is less than 19
 Search to the RIGHT (cuz 19 MUST then be to the right)
index 0 1 2 3 4 5 6 7 8
value 2 6 19 27 33 37 38 41 118
And More Recursion page 3
© Dr. Jonathan (Yahya) Cazalas
Binary Search – A reminder
 Array Search
 We are given the following sorted array:
 We are searching for the value, 19
 So, we MUST start the search in the middle
INDEX of the array.
 In this case:
 The lowest index is 0
 The highest index is 8
 So the middle index is 4
index 0 1 2 3 4 5 6 7 8
value 2 6 19 27 33 37 38 41 118
And More Recursion page 4
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Array Search
 Correct Strategy
 We would ask, “is the number I am searching for, 19,
greater or less than the number stored in index 4?
 Index 4 stores 33
 The answer would be “less than”
 So we would modify our search range to in between
index 0 and index 3
 Note that index 4 is no longer in the search space
 We then continue this process
 The second index we’d look at is index 1, since (0+3)/2=1
 Then we’d finally get to index 2, since (2+3)/2 = 2
 And at index 2, we would find the value, 19, in the array
And More Recursion page 5
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Binary Search code:
public static int binSearch(int[] a, int value) {
int low = 0;
int high = a.length;
while (low <= high) {
int mid = (low + high)/2;
if (a[mid] == value)
return 1; // return 1 if found
else if (a[mid] < value)
low = mid + 1;
else
high = mid - 1;
}
return 0; // this only happens if not found
And More Recursion page 6
© Dr. Jonathan (Yahya) Cazalas
Binary Search
 Binary Search code:
 At the end of each array iteration, all we do is
update either low or high
 This modifies our search region
 Essentially halving it
 As we saw previously, this runs in log n time
 But this iterative code isn’t the easiest to read
 We now look at the recursive code
 MUCH easier to read and understand
And More Recursion page 7
© Dr. Jonathan (Yahya) Cazalas
Binary Search – Recursive
 Binary Search using recursion:
 We need a stopping case:
 We need to STOP the recursion at some point
 So when do we stop:
1) When the number is found!
2) Or when the search range is nothing
 huh?
 The search range is empty when (low > high)
 So how let us look at the code…
And More Recursion page 8
© Dr. Jonathan (Yahya) Cazalas
Binary Search – Recursive
 Binary Search Code (using recursion):
 We see how this code follows from the
explanation of binary search quite easily
public static int binSearch(int[] a, int low, int high, int searchVal) {
int mid;
if (low <= high) {
mid = (low+high)/2;
if (searchVal < a[mid])
return binSearch(a, low, mid-1, searchVal);
else if (searchVal > a[mid])
return binSearch(a, mid+1, high, searchVal);
else
return 1;
}
return 0;
}
And More Recursion page 9
© Dr. Jonathan (Yahya) Cazalas
Binary Search – Recursive
 Binary Search Code (using recursion):
 So if the value is found
 We return 1
 Otherwise,
 if (searchVal < a[mid])
 Then recursively call binSearch to the LEFT
 else if (searchVal > a[mid])
 Then recursively call binSearch to the RIGHT
 If low ever becomes greater than high
 This means that searchVal is NOT in the array
And More Recursion page 10
© Dr. Jonathan (Yahya) Cazalas
Brief Interlude: Human Stupidity
And More Recursion page 11
© Dr. Jonathan (Yahya) Cazalas
Recursive Exponentiation
 Example from Previous lecture
 Our function:
 Calculates be
 Some base raised to a power, e
 The input is the base, b, and the exponent, e
 So if the input was 2 for the base and 4 for the exponent
 The answer would be 24 = 16
 How do we do this recursively?
 We need to solve this in such a way that part of the
solution is a sub-problem of the EXACT same nature of
the original problem.
And More Recursion page 12
© Dr. Jonathan (Yahya) Cazalas
Recursive Exponentiation
 Example from Previous lecture
 Our function:
 Using b and e as input, here is our function
 f(b,e) = be
 So to make this recursive, can we say:
 f(b,e) = be = b*b(e-1)
 Does that “look” recursive?
 YES it does!
 Why?
 Cuz the right side is indeed a sub-problem of the original
 We want to evaluate be
 And our right side evaluates b(e-1)
And More Recursion page 13
© Dr. Jonathan (Yahya) Cazalas
Recursive Exponentiation
 Example from Previous lecture
 Our function:
 f(b,e) = b*b(e-1)
 So we need to determine the terminating condition!
 We know that f(b,0) = b0 = 1
 So our terminating condition can be when e = 1
 Additionally, our recursive calls need to return an
expression for f(b,e) in terms of f(b,k)
 for some k < e
 We just found that f(b,e) = b*b(e-1)
 So now we can write our actual function…
And More Recursion page 14
© Dr. Jonathan (Yahya) Cazalas
Recursive Exponentiation
 Example from Previous lecture
 Code:
// Pre-conditions: e is greater than or equal to 0.
// Post-conditions: returns be.
public static int Power(int base, int exponent) {
if ( exponent == 0 )
return 1;
else
return (base*Power(base, exponent-1));
}
And More Recursion page 15
© Dr. Jonathan (Yahya) Cazalas
Recursive Exponentiation
 Example from Previous lecture
 Say we initially call the function with 2 as our base
and 8 as the exponent
 The final return will be
 return 2*2*2*2*2*2*2*2
 Which equals 256
 You notice we have 7 multiplications (exp was 8)
 The number of multiplications needed is one less
than the exponent value
 So if n was the exponent
 The # of multiplications needed would be n-1
And More Recursion page 16
© Dr. Jonathan (Yahya) Cazalas
Fast Exponentiation
 Example from Previous lecture
 This works just fine
 BUT, it becomes VERY slow for large exponents
 If the exponent was 10,000, that would be 9,999 mults!
 How can we do better?
 One key idea:
 Remembering the laws of exponents
 Yeah, algebra…the thing you forgot about two years ago
 So using the laws of exponents
 We remember that 28 = 24*24
And More Recursion page 17
© Dr. Jonathan (Yahya) Cazalas
Fast Exponentiation
 Example from Previous lecture
 One key idea:
 Remembering the laws of exponents
 28 = 24*24
 Now, if we know 24
 we can calculate 28 with one multiplication
 What is 24?
 24 = 22*22
 and 22 = 2*(2)
 So… 2*(2) = 4, 4*(4) = 16, 16*(16) = 256 = 28
 So we’ve calculated 28 using only three multiplications
 MUCH better than 7 multiplications
And More Recursion page 18
© Dr. Jonathan (Yahya) Cazalas
Fast Exponentiation
 Example of Fast Exponentiation
 So, in general, we can say:
 bn = bn/2*bn/2
 So to find bn, we find bn/2
 HALF of the original amount
 And to find bn/2, we find bn/4
 Again, HALF of bn/2
 This smells like a log n running time
 log n number of multiplications
 Much better than n multiplications
 But as of now, this only works if n is even
And More Recursion page 19
© Dr. Jonathan (Yahya) Cazalas
Fast Exponentiation
 Example of Fast Exponentiation
 So, in general, we can say:
 bn = bn/2*bn/2
 This works when n is even
 But what if n is odd?
 Notice that 29 = 24*24*2
 So, in general, we can say:
/ 2 / 2
/ 2 / 2
( ) if n is even
( )( ) if n is odd
n n
n
n n
a a
a
a a a

= 

And More Recursion page 20
© Dr. Jonathan (Yahya) Cazalas
Fast Exponentiation
 Example of Fast Exponentiation
 Also, this method relies on “integer division”
 We’ve briefly discussed this
 Basically if n is 9, then n/2 = 4
 Integer division
 Think of it as dividing
 AND then rounding down, if needed, to the nearest integer
 So if n is 121, then n/2 = 60
 Finally, if n is 57, then n/2 = 28
 Using the same base case as the previous
power function, here is the code…
And More Recursion page 21
© Dr. Jonathan (Yahya) Cazalas
Fast Exponentiation
 Example of Fast Exponentiation
 Code:
Public static int powerB(int base, int exp) {
if (exp == 0)
return 1;
else if (exp == 1)
return base;
else if (exp%2 == 0)
return powerB(base*base, exp/2);
else
return base*powerB(base, exp-1);
}
And More Recursion page 22
© Dr. Jonathan (Yahya) Cazalas
Recursion
WASN’T
THAT
BODACIOUS!
And More Recursion page 23
© Dr. Jonathan (Yahya) Cazalas
Daily Demotivator
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
And More
Recursion

More Related Content

What's hot

L3
L3L3
L3
lksoo
 
Lecture 5: Neural Networks II
Lecture 5: Neural Networks IILecture 5: Neural Networks II
Lecture 5: Neural Networks II
Sang Jun Lee
 
Lesson 6 recursion
Lesson 6  recursionLesson 6  recursion
Lesson 6 recursion
MLG College of Learning, Inc
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
Hanif Durad
 
Lesson 4 stacks and queues
Lesson 4  stacks and queuesLesson 4  stacks and queues
Lesson 4 stacks and queues
MLG College of Learning, Inc
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
Intro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
Lesson 2.2 abstraction
Lesson 2.2   abstractionLesson 2.2   abstraction
Lesson 2.2 abstraction
MLG College of Learning, Inc
 
07slide
07slide07slide
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
Shakil Ahmed
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
RacksaviR
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query Expressions
Chris Eargle
 
Java - Arrays Concepts
Java - Arrays ConceptsJava - Arrays Concepts
Java - Arrays Concepts
Victer Paul
 
Knowledge Representation, Inference and Reasoning
Knowledge Representation, Inference and ReasoningKnowledge Representation, Inference and Reasoning
Knowledge Representation, Inference and Reasoning
Sagacious IT Solution
 
Domain Examination of Chaos Logistics Function As A Key Generator in Cryptogr...
Domain Examination of Chaos Logistics Function As A Key Generator in Cryptogr...Domain Examination of Chaos Logistics Function As A Key Generator in Cryptogr...
Domain Examination of Chaos Logistics Function As A Key Generator in Cryptogr...
IJECEIAES
 
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Dheeraj Kataria
 
algorithm unit 1
algorithm unit 1algorithm unit 1
algorithm unit 1
Monika Choudhery
 
algorithm Unit 5
algorithm Unit 5 algorithm Unit 5
algorithm Unit 5
Monika Choudhery
 
Lesson 2.1 array
Lesson 2.1   arrayLesson 2.1   array
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
Monika Choudhery
 

What's hot (20)

L3
L3L3
L3
 
Lecture 5: Neural Networks II
Lecture 5: Neural Networks IILecture 5: Neural Networks II
Lecture 5: Neural Networks II
 
Lesson 6 recursion
Lesson 6  recursionLesson 6  recursion
Lesson 6 recursion
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
 
Lesson 4 stacks and queues
Lesson 4  stacks and queuesLesson 4  stacks and queues
Lesson 4 stacks and queues
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
Lesson 2.2 abstraction
Lesson 2.2   abstractionLesson 2.2   abstraction
Lesson 2.2 abstraction
 
07slide
07slide07slide
07slide
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 
Binary search tree
Binary search treeBinary search tree
Binary search tree
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query Expressions
 
Java - Arrays Concepts
Java - Arrays ConceptsJava - Arrays Concepts
Java - Arrays Concepts
 
Knowledge Representation, Inference and Reasoning
Knowledge Representation, Inference and ReasoningKnowledge Representation, Inference and Reasoning
Knowledge Representation, Inference and Reasoning
 
Domain Examination of Chaos Logistics Function As A Key Generator in Cryptogr...
Domain Examination of Chaos Logistics Function As A Key Generator in Cryptogr...Domain Examination of Chaos Logistics Function As A Key Generator in Cryptogr...
Domain Examination of Chaos Logistics Function As A Key Generator in Cryptogr...
 
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
 
algorithm unit 1
algorithm unit 1algorithm unit 1
algorithm unit 1
 
algorithm Unit 5
algorithm Unit 5 algorithm Unit 5
algorithm Unit 5
 
Lesson 2.1 array
Lesson 2.1   arrayLesson 2.1   array
Lesson 2.1 array
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 

Similar to recursion3

binary_search
binary_searchbinary_search
binary_search
Mohamed Elsayed
 
heaps2
heaps2heaps2
Based on the readings and content for this course.docxBased on.docx
Based on the readings and content for this course.docxBased on.docxBased on the readings and content for this course.docxBased on.docx
Based on the readings and content for this course.docxBased on.docx
ikirkton
 
Introduction to Dynamic Programming.pptx
Introduction to Dynamic Programming.pptxIntroduction to Dynamic Programming.pptx
Introduction to Dynamic Programming.pptx
PochupouOwo
 
C12 bst
C12 bstC12 bst
C12 bst
C12 bstC12 bst
Exploring Algorithms
Exploring AlgorithmsExploring Algorithms
Exploring Algorithms
Sri Prasanna
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
Jay Nagar
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
Sure Interview
 
Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
Flavia Tembo Kambale
 
Binary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick TreeBinary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick Tree
Mohammed Ashiqur Rahman Baig
 
Recursion
RecursionRecursion
Recursion
Syed Zaid Irshad
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
Andres Mendez-Vazquez
 
Relational Algebra & Calculus
Relational Algebra & CalculusRelational Algebra & Calculus
Relational Algebra & Calculus
Abdullah Khosa
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
ramya marichamy
 
algorithm_analysis1
algorithm_analysis1algorithm_analysis1
algorithm_analysis1
Mohamed Elsayed
 
Algorithm in computer science
Algorithm in computer scienceAlgorithm in computer science
Algorithm in computer science
Riazul Islam
 
Tower of Hanoi.ppt
Tower of Hanoi.pptTower of Hanoi.ppt
Tower of Hanoi.ppt
SACHINVERMA255386
 
lec18_ref.pdf
lec18_ref.pdflec18_ref.pdf
lec18_ref.pdf
vishal choudhary
 
Introduction to Real Analysis 4th Edition Bartle Solutions Manual
Introduction to Real Analysis 4th Edition Bartle Solutions ManualIntroduction to Real Analysis 4th Edition Bartle Solutions Manual
Introduction to Real Analysis 4th Edition Bartle Solutions Manual
DawsonVeronica
 

Similar to recursion3 (20)

binary_search
binary_searchbinary_search
binary_search
 
heaps2
heaps2heaps2
heaps2
 
Based on the readings and content for this course.docxBased on.docx
Based on the readings and content for this course.docxBased on.docxBased on the readings and content for this course.docxBased on.docx
Based on the readings and content for this course.docxBased on.docx
 
Introduction to Dynamic Programming.pptx
Introduction to Dynamic Programming.pptxIntroduction to Dynamic Programming.pptx
Introduction to Dynamic Programming.pptx
 
C12 bst
C12 bstC12 bst
C12 bst
 
C12 bst
C12 bstC12 bst
C12 bst
 
Exploring Algorithms
Exploring AlgorithmsExploring Algorithms
Exploring Algorithms
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
 
Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
 
Binary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick TreeBinary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick Tree
 
Recursion
RecursionRecursion
Recursion
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
 
Relational Algebra & Calculus
Relational Algebra & CalculusRelational Algebra & Calculus
Relational Algebra & Calculus
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
algorithm_analysis1
algorithm_analysis1algorithm_analysis1
algorithm_analysis1
 
Algorithm in computer science
Algorithm in computer scienceAlgorithm in computer science
Algorithm in computer science
 
Tower of Hanoi.ppt
Tower of Hanoi.pptTower of Hanoi.ppt
Tower of Hanoi.ppt
 
lec18_ref.pdf
lec18_ref.pdflec18_ref.pdf
lec18_ref.pdf
 
Introduction to Real Analysis 4th Edition Bartle Solutions Manual
Introduction to Real Analysis 4th Edition Bartle Solutions ManualIntroduction to Real Analysis 4th Edition Bartle Solutions Manual
Introduction to Real Analysis 4th Edition Bartle Solutions Manual
 

More from Mohamed Elsayed

binary_trees3
binary_trees3binary_trees3
binary_trees3
Mohamed Elsayed
 
binary_trees1
binary_trees1binary_trees1
binary_trees1
Mohamed Elsayed
 
queues
queuesqueues
stacks2
stacks2stacks2
stacks1
stacks1stacks1
algorithm_analysis2
algorithm_analysis2algorithm_analysis2
algorithm_analysis2
Mohamed Elsayed
 
linked_lists4
linked_lists4linked_lists4
linked_lists4
Mohamed Elsayed
 
linked_lists3
linked_lists3linked_lists3
linked_lists3
Mohamed Elsayed
 
Linked_lists2
Linked_lists2Linked_lists2
Linked_lists2
Mohamed Elsayed
 
linked_lists
linked_listslinked_lists
linked_lists
Mohamed Elsayed
 
sorted_listmatch
sorted_listmatchsorted_listmatch
sorted_listmatch
Mohamed Elsayed
 
arrays
arraysarrays
heaps
heapsheaps
hash_tables
hash_tableshash_tables
hash_tables
Mohamed Elsayed
 
graphs
graphsgraphs
quick_sort
quick_sortquick_sort
quick_sort
Mohamed Elsayed
 
merge_sort
merge_sortmerge_sort
merge_sort
Mohamed Elsayed
 
n-squared_sorts
n-squared_sortsn-squared_sorts
n-squared_sorts
Mohamed Elsayed
 

More from Mohamed Elsayed (18)

binary_trees3
binary_trees3binary_trees3
binary_trees3
 
binary_trees1
binary_trees1binary_trees1
binary_trees1
 
queues
queuesqueues
queues
 
stacks2
stacks2stacks2
stacks2
 
stacks1
stacks1stacks1
stacks1
 
algorithm_analysis2
algorithm_analysis2algorithm_analysis2
algorithm_analysis2
 
linked_lists4
linked_lists4linked_lists4
linked_lists4
 
linked_lists3
linked_lists3linked_lists3
linked_lists3
 
Linked_lists2
Linked_lists2Linked_lists2
Linked_lists2
 
linked_lists
linked_listslinked_lists
linked_lists
 
sorted_listmatch
sorted_listmatchsorted_listmatch
sorted_listmatch
 
arrays
arraysarrays
arrays
 
heaps
heapsheaps
heaps
 
hash_tables
hash_tableshash_tables
hash_tables
 
graphs
graphsgraphs
graphs
 
quick_sort
quick_sortquick_sort
quick_sort
 
merge_sort
merge_sortmerge_sort
merge_sort
 
n-squared_sorts
n-squared_sortsn-squared_sorts
n-squared_sorts
 

Recently uploaded

Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 

Recently uploaded (20)

Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 

recursion3

  • 1. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I And More Recursion
  • 2. And More Recursion page 2 © Dr. Jonathan (Yahya) Cazalas Binary Search – A reminder  Array Search  We are given the following sorted array:  We are searching for the value, 19 (for example)  Remember, we said that you search the middle element  If found, you are done  If the element in the middle is greater than 19  Search to the LEFT (cuz 19 MUST be to the left)  If the element in the middle is less than 19  Search to the RIGHT (cuz 19 MUST then be to the right) index 0 1 2 3 4 5 6 7 8 value 2 6 19 27 33 37 38 41 118
  • 3. And More Recursion page 3 © Dr. Jonathan (Yahya) Cazalas Binary Search – A reminder  Array Search  We are given the following sorted array:  We are searching for the value, 19  So, we MUST start the search in the middle INDEX of the array.  In this case:  The lowest index is 0  The highest index is 8  So the middle index is 4 index 0 1 2 3 4 5 6 7 8 value 2 6 19 27 33 37 38 41 118
  • 4. And More Recursion page 4 © Dr. Jonathan (Yahya) Cazalas Binary Search  Array Search  Correct Strategy  We would ask, “is the number I am searching for, 19, greater or less than the number stored in index 4?  Index 4 stores 33  The answer would be “less than”  So we would modify our search range to in between index 0 and index 3  Note that index 4 is no longer in the search space  We then continue this process  The second index we’d look at is index 1, since (0+3)/2=1  Then we’d finally get to index 2, since (2+3)/2 = 2  And at index 2, we would find the value, 19, in the array
  • 5. And More Recursion page 5 © Dr. Jonathan (Yahya) Cazalas Binary Search  Binary Search code: public static int binSearch(int[] a, int value) { int low = 0; int high = a.length; while (low <= high) { int mid = (low + high)/2; if (a[mid] == value) return 1; // return 1 if found else if (a[mid] < value) low = mid + 1; else high = mid - 1; } return 0; // this only happens if not found
  • 6. And More Recursion page 6 © Dr. Jonathan (Yahya) Cazalas Binary Search  Binary Search code:  At the end of each array iteration, all we do is update either low or high  This modifies our search region  Essentially halving it  As we saw previously, this runs in log n time  But this iterative code isn’t the easiest to read  We now look at the recursive code  MUCH easier to read and understand
  • 7. And More Recursion page 7 © Dr. Jonathan (Yahya) Cazalas Binary Search – Recursive  Binary Search using recursion:  We need a stopping case:  We need to STOP the recursion at some point  So when do we stop: 1) When the number is found! 2) Or when the search range is nothing  huh?  The search range is empty when (low > high)  So how let us look at the code…
  • 8. And More Recursion page 8 © Dr. Jonathan (Yahya) Cazalas Binary Search – Recursive  Binary Search Code (using recursion):  We see how this code follows from the explanation of binary search quite easily public static int binSearch(int[] a, int low, int high, int searchVal) { int mid; if (low <= high) { mid = (low+high)/2; if (searchVal < a[mid]) return binSearch(a, low, mid-1, searchVal); else if (searchVal > a[mid]) return binSearch(a, mid+1, high, searchVal); else return 1; } return 0; }
  • 9. And More Recursion page 9 © Dr. Jonathan (Yahya) Cazalas Binary Search – Recursive  Binary Search Code (using recursion):  So if the value is found  We return 1  Otherwise,  if (searchVal < a[mid])  Then recursively call binSearch to the LEFT  else if (searchVal > a[mid])  Then recursively call binSearch to the RIGHT  If low ever becomes greater than high  This means that searchVal is NOT in the array
  • 10. And More Recursion page 10 © Dr. Jonathan (Yahya) Cazalas Brief Interlude: Human Stupidity
  • 11. And More Recursion page 11 © Dr. Jonathan (Yahya) Cazalas Recursive Exponentiation  Example from Previous lecture  Our function:  Calculates be  Some base raised to a power, e  The input is the base, b, and the exponent, e  So if the input was 2 for the base and 4 for the exponent  The answer would be 24 = 16  How do we do this recursively?  We need to solve this in such a way that part of the solution is a sub-problem of the EXACT same nature of the original problem.
  • 12. And More Recursion page 12 © Dr. Jonathan (Yahya) Cazalas Recursive Exponentiation  Example from Previous lecture  Our function:  Using b and e as input, here is our function  f(b,e) = be  So to make this recursive, can we say:  f(b,e) = be = b*b(e-1)  Does that “look” recursive?  YES it does!  Why?  Cuz the right side is indeed a sub-problem of the original  We want to evaluate be  And our right side evaluates b(e-1)
  • 13. And More Recursion page 13 © Dr. Jonathan (Yahya) Cazalas Recursive Exponentiation  Example from Previous lecture  Our function:  f(b,e) = b*b(e-1)  So we need to determine the terminating condition!  We know that f(b,0) = b0 = 1  So our terminating condition can be when e = 1  Additionally, our recursive calls need to return an expression for f(b,e) in terms of f(b,k)  for some k < e  We just found that f(b,e) = b*b(e-1)  So now we can write our actual function…
  • 14. And More Recursion page 14 © Dr. Jonathan (Yahya) Cazalas Recursive Exponentiation  Example from Previous lecture  Code: // Pre-conditions: e is greater than or equal to 0. // Post-conditions: returns be. public static int Power(int base, int exponent) { if ( exponent == 0 ) return 1; else return (base*Power(base, exponent-1)); }
  • 15. And More Recursion page 15 © Dr. Jonathan (Yahya) Cazalas Recursive Exponentiation  Example from Previous lecture  Say we initially call the function with 2 as our base and 8 as the exponent  The final return will be  return 2*2*2*2*2*2*2*2  Which equals 256  You notice we have 7 multiplications (exp was 8)  The number of multiplications needed is one less than the exponent value  So if n was the exponent  The # of multiplications needed would be n-1
  • 16. And More Recursion page 16 © Dr. Jonathan (Yahya) Cazalas Fast Exponentiation  Example from Previous lecture  This works just fine  BUT, it becomes VERY slow for large exponents  If the exponent was 10,000, that would be 9,999 mults!  How can we do better?  One key idea:  Remembering the laws of exponents  Yeah, algebra…the thing you forgot about two years ago  So using the laws of exponents  We remember that 28 = 24*24
  • 17. And More Recursion page 17 © Dr. Jonathan (Yahya) Cazalas Fast Exponentiation  Example from Previous lecture  One key idea:  Remembering the laws of exponents  28 = 24*24  Now, if we know 24  we can calculate 28 with one multiplication  What is 24?  24 = 22*22  and 22 = 2*(2)  So… 2*(2) = 4, 4*(4) = 16, 16*(16) = 256 = 28  So we’ve calculated 28 using only three multiplications  MUCH better than 7 multiplications
  • 18. And More Recursion page 18 © Dr. Jonathan (Yahya) Cazalas Fast Exponentiation  Example of Fast Exponentiation  So, in general, we can say:  bn = bn/2*bn/2  So to find bn, we find bn/2  HALF of the original amount  And to find bn/2, we find bn/4  Again, HALF of bn/2  This smells like a log n running time  log n number of multiplications  Much better than n multiplications  But as of now, this only works if n is even
  • 19. And More Recursion page 19 © Dr. Jonathan (Yahya) Cazalas Fast Exponentiation  Example of Fast Exponentiation  So, in general, we can say:  bn = bn/2*bn/2  This works when n is even  But what if n is odd?  Notice that 29 = 24*24*2  So, in general, we can say: / 2 / 2 / 2 / 2 ( ) if n is even ( )( ) if n is odd n n n n n a a a a a a  =  
  • 20. And More Recursion page 20 © Dr. Jonathan (Yahya) Cazalas Fast Exponentiation  Example of Fast Exponentiation  Also, this method relies on “integer division”  We’ve briefly discussed this  Basically if n is 9, then n/2 = 4  Integer division  Think of it as dividing  AND then rounding down, if needed, to the nearest integer  So if n is 121, then n/2 = 60  Finally, if n is 57, then n/2 = 28  Using the same base case as the previous power function, here is the code…
  • 21. And More Recursion page 21 © Dr. Jonathan (Yahya) Cazalas Fast Exponentiation  Example of Fast Exponentiation  Code: Public static int powerB(int base, int exp) { if (exp == 0) return 1; else if (exp == 1) return base; else if (exp%2 == 0) return powerB(base*base, exp/2); else return base*powerB(base, exp-1); }
  • 22. And More Recursion page 22 © Dr. Jonathan (Yahya) Cazalas Recursion WASN’T THAT BODACIOUS!
  • 23. And More Recursion page 23 © Dr. Jonathan (Yahya) Cazalas Daily Demotivator
  • 24. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I And More Recursion