SlideShare a Scribd company logo
1 of 27
Introduction to algorithms
1
University of Technology and Engineering
Vietnam National University Hanoi
Algorithms?
What is an algorithm?
An algorithm is a step by step procedure to solve a problem. An algorithm
can be described by nature languages or programming languages.
Example: How to cook rice?
❖ Step 1: Get rice
❖ Step 2: Rinse the rice
❖ Step 3: Put the rice and water into a rice cooker
❖ Step 4: Turn on the rice cooker
❖ Step 5: Check the rice when the rice cooker turns off
2
Algorithms?
What is a good algorithm?
❖Correctness
❖Efficiency
❖Simple/understandable
❖Implementable
3
Algorithms
4
How to design algorithm?
➢ Step 1: Define the problem clearly
➢ Step 2: Analyze the problem from
different perspectives and constrains.
➢ Step 3: Use popular techniques and
strategies:
❖ Basic algorithms
❖ Brute force algorithms
❖ Greedy algorithms
❖ Divide and conquer
❖ Dynamic programming
❖ Graph theories
❖ String/text processing algorithms
➢ Step 4: Use flow chart to represent
algorithms
5
Searching problem
Problem: Given a list A consisting of n items. Check if an item X
exists on list A?
Simple search algorithm: Iterate from the begin to the end of A to
check if X equals to any item of A.
Complexity: O(n)
6
Sorting problem
Problem: Given a list A consisting of n items. Sort items of list
A increasingly?
Example:
A = (1, 2, 5, 3, 8, 9, 2)
Sorting result:
A = (1, 2, 2, 3, 5, 8, 9)
7
Selection sort
Algorithm
➢ The list is divided into two parts:
sorted part and unsorted part.
➢ Repeatedly finding the minimum
element from unsorted part and
moving it to the end of the sorted
part.
8
Selection sort
Algorithm selection_sort (A, n):
for iter from 0 to n - 2 do
min_idx = iter;
for idx from (iter + 1) to n - 1 do
if A[idx] < A[min_idx] then
min_idx = idx;
swap (a[iter], a[min_idx]);
Complexity:
9
Searching on sorted list
Problem: Given a list A consisting of n items sorted increasingly.
Check if an item X exists on list A?
Binary search algorithm (A):
❖ If A is empty, return False
❖ Compare X with the item Y at the middle of A.
• If X = Y, return True.
• If X < Y, Perform binary search on the left half of A
• If X > Y, Perform binary search on the right half of A
Complexity: 10
Example
11
1 3 4 5 7 8 9 11 14 16 18 19
1 3 4 5 7 8 9 11 14 16 18 19
1 3 4 5 7 8 9 11 14 16 18 19
1 3 4 5 7 8 9 11 14 16 18 19
0
0
0
0
m
l r
m
l
r
m
l r
l=m =r
Brute Force Search
Systematically evaluate all possible solutions for the
problem to determine objective solutions.
Example:
❖ Find all prime numbers smaller than 100
❖ Find all binary numbers of length n
12
The largest row
Problem: Given a matrix A of m rows and n columns
containing integer numbers. Your task is to find the
row with the largest sum.
Method Find_largest_row (A, m, n):
Complexity:
13
The largest rectangle
Problem: Given a matrix of A of m rows and n
columns containing integer numbers. Your task is to
find the rectangle in the matrix with the largest sum.
Method Find_largest_rectangle (A, m, n):
Complexity:
14
Recursion
➢ Recursion: when a method calls itself
Classic example (the factorial function):
n! = n * (n-1)!
➢ Recursive definition:
Algorithm RecursiveFactorial (int n) {
if (n == 0) return 1; // base case
else return n * RecursiveFactorial (n - 1); // recursive case
}
15
Content of a Recursive Method
➢ Base case(s).
❖ The cases for which we perform no recursive calls
❖ Every possible chain of recursive calls must eventually reach
a base case.
➢ Recursive calls.
❖ Calls to the current method.
❖ Each recursive call should be defined so that it makes
progress towards a base case.
16
Visualizing Recursion
recursiveFactorial (4 )
recursiveFactorial (3 )
recursiveFactorial (2 )
recursiveFactorial (1 )
recursiveFactorial (0 )
return 1
call
call
call
call
return 1 *1 = 1
return 2 *1 = 2
return 3 *2 = 6
return 4 *6 = 24 final answer
call
17
Computing Powers
➢ The power function, p(x, n) = xn, can be defined recursively:
➢ This leads to an power function that runs in O(n) time
18
Recursive Squaring
➢We can derive a more efficient linearly
recursive algorithm by using repeated squaring:
➢For example,
24 = 2(4/2)2 = (24/2)2 = (22)2 = 42 = 16
25 = 21+(4/2)2 = 2(24/2)2 = 2(22)2 = 2(42) = 32
26 = 2(6/ 2)2 = (26/2)2 = (23)2 = 82 = 64
27 = 21+(6/2)2 = 2(26/2)2 = 2(23)2 = 2(82) = 128.
19
A Recursive Squaring Method
Algorithm Power(x, n):
Input: A number x and integer n = 0
Output: The value xn
if n = 0 then
return 1;
if n is odd then
y = Power(x, (n - 1)/ 2);
return x · y ·y;
else
y = Power(x, n/ 2);
return y · y; 20
Analyzing the Recursive Squaring
Method
Algorithm Power(x, n):
Input: A number x and integer
n = 0
Output: The value xn
if n = 0 then
return 1;
if n is odd then
y = Power(x, (n - 1)/ 2);
return x · y · y;
else
y = Power(x, n/ 2);
return y · y;
It is important that we
used a variable twice here
rather than calling the
method twice.
Each time we make a
recursive call we halve the
value of n; hence, we make
log n recursive calls. That
is, this method runs in
O(log n) time.
21
Find all binary numbers
Problem: Find all binary numbers of length n.
Example: n = 3
000,001,010,011,100,101,110,111
Algorithm binary_number(b, k, n):
for v for 0 to 1 do
b[k] = v;
if (k==n) then
print b;
else
binary number (b, k + 1, n);
Complexity: 22
23
24
25
26
Find permutations
Problem: Find all permutations of length n.
Example: n = 3
123, 132, 213, 231, 312, 321
Algorithm: Find_permutations (n):
Complexity:
23

More Related Content

Similar to Lecture 7_introduction_algorithms.pptx

Similar to Lecture 7_introduction_algorithms.pptx (20)

Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
13 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp0213 recursion-120712074623-phpapp02
13 recursion-120712074623-phpapp02
 
Optimization tutorial
Optimization tutorialOptimization tutorial
Optimization tutorial
 
Research Inventy : International Journal of Engineering and Science
Research Inventy : International Journal of Engineering and ScienceResearch Inventy : International Journal of Engineering and Science
Research Inventy : International Journal of Engineering and Science
 
Perform brute force
Perform brute forcePerform brute force
Perform brute force
 
algo_vc_lecture8.ppt
algo_vc_lecture8.pptalgo_vc_lecture8.ppt
algo_vc_lecture8.ppt
 
Ada notes
Ada notesAda notes
Ada notes
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 
Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
 
Algorithms
AlgorithmsAlgorithms
Algorithms
 
Analysis of algorithms
Analysis of algorithmsAnalysis of algorithms
Analysis of algorithms
 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
 
lecture 10
lecture 10lecture 10
lecture 10
 
Solution 3.
Solution 3.Solution 3.
Solution 3.
 
Tower of Hanoi.ppt
Tower of Hanoi.pptTower of Hanoi.ppt
Tower of Hanoi.ppt
 
Recursion
RecursionRecursion
Recursion
 
Matlab tutorial 2
Matlab tutorial 2Matlab tutorial 2
Matlab tutorial 2
 
Unit 4
Unit 4Unit 4
Unit 4
 
Unit 4
Unit 4Unit 4
Unit 4
 

Recently uploaded

DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24  Building Real-Time Pipelines With FLaNKDATA SUMMIT 24  Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNKTimothy Spann
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...nirzagarg
 
20240412-SmartCityIndex-2024-Full-Report.pdf
20240412-SmartCityIndex-2024-Full-Report.pdf20240412-SmartCityIndex-2024-Full-Report.pdf
20240412-SmartCityIndex-2024-Full-Report.pdfkhraisr
 
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...HyderabadDolls
 
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...ThinkInnovation
 
Vastral Call Girls Book Now 7737669865 Top Class Escort Service Available
Vastral Call Girls Book Now 7737669865 Top Class Escort Service AvailableVastral Call Girls Book Now 7737669865 Top Class Escort Service Available
Vastral Call Girls Book Now 7737669865 Top Class Escort Service Availablegargpaaro
 
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...gajnagarg
 
7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.ppt7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.pptibrahimabdi22
 
Giridih Escorts Service Girl ^ 9332606886, WhatsApp Anytime Giridih
Giridih Escorts Service Girl ^ 9332606886, WhatsApp Anytime GiridihGiridih Escorts Service Girl ^ 9332606886, WhatsApp Anytime Giridih
Giridih Escorts Service Girl ^ 9332606886, WhatsApp Anytime Giridihmeghakumariji156
 
Dubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls DubaiDubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls Dubaikojalkojal131
 
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...kumargunjan9515
 
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...nirzagarg
 
Diamond Harbour \ Russian Call Girls Kolkata | Book 8005736733 Extreme Naught...
Diamond Harbour \ Russian Call Girls Kolkata | Book 8005736733 Extreme Naught...Diamond Harbour \ Russian Call Girls Kolkata | Book 8005736733 Extreme Naught...
Diamond Harbour \ Russian Call Girls Kolkata | Book 8005736733 Extreme Naught...HyderabadDolls
 
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...SOFTTECHHUB
 
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...vershagrag
 
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...nirzagarg
 
Digital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham WareDigital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham WareGraham Ware
 
Top Call Girls in Balaghat 9332606886Call Girls Advance Cash On Delivery Ser...
Top Call Girls in Balaghat  9332606886Call Girls Advance Cash On Delivery Ser...Top Call Girls in Balaghat  9332606886Call Girls Advance Cash On Delivery Ser...
Top Call Girls in Balaghat 9332606886Call Girls Advance Cash On Delivery Ser...kumargunjan9515
 

Recently uploaded (20)

DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24  Building Real-Time Pipelines With FLaNKDATA SUMMIT 24  Building Real-Time Pipelines With FLaNK
DATA SUMMIT 24 Building Real-Time Pipelines With FLaNK
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
Top profile Call Girls In Tumkur [ 7014168258 ] Call Me For Genuine Models We...
 
20240412-SmartCityIndex-2024-Full-Report.pdf
20240412-SmartCityIndex-2024-Full-Report.pdf20240412-SmartCityIndex-2024-Full-Report.pdf
20240412-SmartCityIndex-2024-Full-Report.pdf
 
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
Sonagachi * best call girls in Kolkata | ₹,9500 Pay Cash 8005736733 Free Home...
 
Abortion pills in Jeddah | +966572737505 | Get Cytotec
Abortion pills in Jeddah | +966572737505 | Get CytotecAbortion pills in Jeddah | +966572737505 | Get Cytotec
Abortion pills in Jeddah | +966572737505 | Get Cytotec
 
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
Identify Customer Segments to Create Customer Offers for Each Segment - Appli...
 
Vastral Call Girls Book Now 7737669865 Top Class Escort Service Available
Vastral Call Girls Book Now 7737669865 Top Class Escort Service AvailableVastral Call Girls Book Now 7737669865 Top Class Escort Service Available
Vastral Call Girls Book Now 7737669865 Top Class Escort Service Available
 
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
 
7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.ppt7. Epi of Chronic respiratory diseases.ppt
7. Epi of Chronic respiratory diseases.ppt
 
Giridih Escorts Service Girl ^ 9332606886, WhatsApp Anytime Giridih
Giridih Escorts Service Girl ^ 9332606886, WhatsApp Anytime GiridihGiridih Escorts Service Girl ^ 9332606886, WhatsApp Anytime Giridih
Giridih Escorts Service Girl ^ 9332606886, WhatsApp Anytime Giridih
 
Dubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls DubaiDubai Call Girls Peeing O525547819 Call Girls Dubai
Dubai Call Girls Peeing O525547819 Call Girls Dubai
 
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
 
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
 
Diamond Harbour \ Russian Call Girls Kolkata | Book 8005736733 Extreme Naught...
Diamond Harbour \ Russian Call Girls Kolkata | Book 8005736733 Extreme Naught...Diamond Harbour \ Russian Call Girls Kolkata | Book 8005736733 Extreme Naught...
Diamond Harbour \ Russian Call Girls Kolkata | Book 8005736733 Extreme Naught...
 
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
 
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
 
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
 
Digital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham WareDigital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham Ware
 
Top Call Girls in Balaghat 9332606886Call Girls Advance Cash On Delivery Ser...
Top Call Girls in Balaghat  9332606886Call Girls Advance Cash On Delivery Ser...Top Call Girls in Balaghat  9332606886Call Girls Advance Cash On Delivery Ser...
Top Call Girls in Balaghat 9332606886Call Girls Advance Cash On Delivery Ser...
 

Lecture 7_introduction_algorithms.pptx

  • 1. Introduction to algorithms 1 University of Technology and Engineering Vietnam National University Hanoi
  • 2. Algorithms? What is an algorithm? An algorithm is a step by step procedure to solve a problem. An algorithm can be described by nature languages or programming languages. Example: How to cook rice? ❖ Step 1: Get rice ❖ Step 2: Rinse the rice ❖ Step 3: Put the rice and water into a rice cooker ❖ Step 4: Turn on the rice cooker ❖ Step 5: Check the rice when the rice cooker turns off 2
  • 3. Algorithms? What is a good algorithm? ❖Correctness ❖Efficiency ❖Simple/understandable ❖Implementable 3
  • 5. How to design algorithm? ➢ Step 1: Define the problem clearly ➢ Step 2: Analyze the problem from different perspectives and constrains. ➢ Step 3: Use popular techniques and strategies: ❖ Basic algorithms ❖ Brute force algorithms ❖ Greedy algorithms ❖ Divide and conquer ❖ Dynamic programming ❖ Graph theories ❖ String/text processing algorithms ➢ Step 4: Use flow chart to represent algorithms 5
  • 6. Searching problem Problem: Given a list A consisting of n items. Check if an item X exists on list A? Simple search algorithm: Iterate from the begin to the end of A to check if X equals to any item of A. Complexity: O(n) 6
  • 7. Sorting problem Problem: Given a list A consisting of n items. Sort items of list A increasingly? Example: A = (1, 2, 5, 3, 8, 9, 2) Sorting result: A = (1, 2, 2, 3, 5, 8, 9) 7
  • 8. Selection sort Algorithm ➢ The list is divided into two parts: sorted part and unsorted part. ➢ Repeatedly finding the minimum element from unsorted part and moving it to the end of the sorted part. 8
  • 9. Selection sort Algorithm selection_sort (A, n): for iter from 0 to n - 2 do min_idx = iter; for idx from (iter + 1) to n - 1 do if A[idx] < A[min_idx] then min_idx = idx; swap (a[iter], a[min_idx]); Complexity: 9
  • 10. Searching on sorted list Problem: Given a list A consisting of n items sorted increasingly. Check if an item X exists on list A? Binary search algorithm (A): ❖ If A is empty, return False ❖ Compare X with the item Y at the middle of A. • If X = Y, return True. • If X < Y, Perform binary search on the left half of A • If X > Y, Perform binary search on the right half of A Complexity: 10
  • 11. Example 11 1 3 4 5 7 8 9 11 14 16 18 19 1 3 4 5 7 8 9 11 14 16 18 19 1 3 4 5 7 8 9 11 14 16 18 19 1 3 4 5 7 8 9 11 14 16 18 19 0 0 0 0 m l r m l r m l r l=m =r
  • 12. Brute Force Search Systematically evaluate all possible solutions for the problem to determine objective solutions. Example: ❖ Find all prime numbers smaller than 100 ❖ Find all binary numbers of length n 12
  • 13. The largest row Problem: Given a matrix A of m rows and n columns containing integer numbers. Your task is to find the row with the largest sum. Method Find_largest_row (A, m, n): Complexity: 13
  • 14. The largest rectangle Problem: Given a matrix of A of m rows and n columns containing integer numbers. Your task is to find the rectangle in the matrix with the largest sum. Method Find_largest_rectangle (A, m, n): Complexity: 14
  • 15. Recursion ➢ Recursion: when a method calls itself Classic example (the factorial function): n! = n * (n-1)! ➢ Recursive definition: Algorithm RecursiveFactorial (int n) { if (n == 0) return 1; // base case else return n * RecursiveFactorial (n - 1); // recursive case } 15
  • 16. Content of a Recursive Method ➢ Base case(s). ❖ The cases for which we perform no recursive calls ❖ Every possible chain of recursive calls must eventually reach a base case. ➢ Recursive calls. ❖ Calls to the current method. ❖ Each recursive call should be defined so that it makes progress towards a base case. 16
  • 17. Visualizing Recursion recursiveFactorial (4 ) recursiveFactorial (3 ) recursiveFactorial (2 ) recursiveFactorial (1 ) recursiveFactorial (0 ) return 1 call call call call return 1 *1 = 1 return 2 *1 = 2 return 3 *2 = 6 return 4 *6 = 24 final answer call 17
  • 18. Computing Powers ➢ The power function, p(x, n) = xn, can be defined recursively: ➢ This leads to an power function that runs in O(n) time 18
  • 19. Recursive Squaring ➢We can derive a more efficient linearly recursive algorithm by using repeated squaring: ➢For example, 24 = 2(4/2)2 = (24/2)2 = (22)2 = 42 = 16 25 = 21+(4/2)2 = 2(24/2)2 = 2(22)2 = 2(42) = 32 26 = 2(6/ 2)2 = (26/2)2 = (23)2 = 82 = 64 27 = 21+(6/2)2 = 2(26/2)2 = 2(23)2 = 2(82) = 128. 19
  • 20. A Recursive Squaring Method Algorithm Power(x, n): Input: A number x and integer n = 0 Output: The value xn if n = 0 then return 1; if n is odd then y = Power(x, (n - 1)/ 2); return x · y ·y; else y = Power(x, n/ 2); return y · y; 20
  • 21. Analyzing the Recursive Squaring Method Algorithm Power(x, n): Input: A number x and integer n = 0 Output: The value xn if n = 0 then return 1; if n is odd then y = Power(x, (n - 1)/ 2); return x · y · y; else y = Power(x, n/ 2); return y · y; It is important that we used a variable twice here rather than calling the method twice. Each time we make a recursive call we halve the value of n; hence, we make log n recursive calls. That is, this method runs in O(log n) time. 21
  • 22. Find all binary numbers Problem: Find all binary numbers of length n. Example: n = 3 000,001,010,011,100,101,110,111 Algorithm binary_number(b, k, n): for v for 0 to 1 do b[k] = v; if (k==n) then print b; else binary number (b, k + 1, n); Complexity: 22
  • 23. 23
  • 24. 24
  • 25. 25
  • 26. 26
  • 27. Find permutations Problem: Find all permutations of length n. Example: n = 3 123, 132, 213, 231, 312, 321 Algorithm: Find_permutations (n): Complexity: 23