0% found this document useful (0 votes)
4 views51 pages

DS_Lecture-Week-3 Recursion & Searching

The document discusses recursion and its applications, including calculating factorials and raising numbers to powers, comparing recursive and iterative methods. It also covers recursive algorithms for linear and binary search, as well as the Towers of Hanoi problem, illustrating the recursive approach to solving these problems. The document highlights the efficiency of recursive solutions, despite their overhead, and provides examples of how recursion can simplify complex tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views51 pages

DS_Lecture-Week-3 Recursion & Searching

The document discusses recursion and its applications, including calculating factorials and raising numbers to powers, comparing recursive and iterative methods. It also covers recursive algorithms for linear and binary search, as well as the Towers of Hanoi problem, illustrating the recursive approach to solving these problems. The document highlights the efficiency of recursive solutions, despite their overhead, and provides examples of how recursion can simplify complex tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Recursion

◼ N factorial
◼ Recursion or Iteration
◼ Which is better?

2
Raising a Number to a Power
1 if N = 0 Example using Definition
AN = A4 = A * A 3
= A * A * A2
A *AN-1 if N > 0
= A * A * A * A1
= A * A * A * A * A0
= A * A* A* A* 1
double powr(double a, int n)
{
if (n == 0)
return 1; Calling powr(a,n)requires exactly n
multiplications
else
return a*powr(a,n-1)
}
Computations can be reduced
◼ A32 = A16 * A16
◼ Requires only half the computations (16 + 1)
◼ When the exponent is odd
◼ A33 = A * ( A16 * A16 )

◼ This should total number of computations.


◼ How much?
int fpow(double a, int n)
{
if (n == 0) return 1;
else
{
if (n%2 == 0)
return fpow(a,n/2) * fpow(a,n/2);
else
return a * fpow(a,n/2) * fpow(a,n/2);
}
}
How much better is it compared to earlier solution?
Recursion vs. iteration

◼ most recursive solutions have a corresponding iterative solution


◼ For example, N! can be calculated with a loop

◼ recursion has the overhead of multiple method invocations

◼ Every time a recursive call is made the parameters need to be stored in


a fixed place in memory

6
Recursion vs. iteration

◼ Thus recursive solutions are more expensive than corresponding


iterative solutions,

7
Recursion vs. iteration

◼ Thus recursive solutions are more expensive than corresponding


iterative solutions,

◼ however, the solutions are often more simple and elegant than iterative
solutions

◼ For many problems only recursive solutions are possible.

8
Linear and Binary Search using
Recursion

9
Linear search using recursion
◼ Problem: If element is found return its index. If
element is not found return – 1 .
◼ Solution: Assign a variable high to last index and
keep on decreasing it everytime. (search from
right side of the array)

◼ What is the base case(stopping case)?


(1) If low > high, return – 1
(2) If item = A[high], return high

◼ What is the continuation case?


reduce the length of array by 1 and make a recursive
call.
Recursive Linear Search

public class linearSearchRecursive {

public int linearSearch(int[] a, int n, int x) {


return linearSearch(a, x, 0, n - 1);
}

private int linearSearch(int[ ] a, int x, int low, int high) {


if (low > high) return -1;
if (a[high] == x) return high;
else
return linearSearch(a, x, low, high - 1);

}
}
11
◼ The algorithm searches each element of the array starting from the last one.
◼ Same list is used, except that its size keeps on reducing every time.
◼ In worst case all the n elements need to be looked at.

12
Recursive Binary Search
public class BinarySearchRecursive {

public int binarySearch(int[] a, int n, int x) {


return binarySearch(a, x, 0, n - 1);
}

private int binarySearch(int[ ] a, int x, int low, int high) {


if (low > high) return -1;

int mid = (low + high)/2;


if (a[mid] == x) return mid;
else if (a[mid] < x)
return binarySearch(a, x, mid+1, high);
else
return binarySearch(a, x, low, mid-1);
}
} 13
Towers of Hanoi

14
Towers of Hanoi
◼ There are three towers
◼ 64 gold disks, with decreasing sizes, placed on the first tower
◼ You need to move all of the disks from the first tower to the last tower
◼ A large disk can not be placed on top of a smaller disk.
◼ The remaining tower can be used to temporarily hold disks
◼ How many operations needed to transfer 7 disks from source tower to
destination tower?

◼ Given that 10 disks can be moved in 1023 operations, how many operations
needed for 11 disks?

16
Class work
◼ Students may try solving the Tower of Hanoi problem using n= 4.
◼ Imagine 4 disks are placed on tower a.
◼ Name the disks 1,2,3,4 starting from top.
◼ You have to move all the disks to tower b.
◼ You can make use of tower c, but note that you cannot put a larger disk on a
smaller disk.

17
Recursive solution
◼ Given n disks, we shall try to solve the problem for n-1 disks first.
◼ That is the recursive way.

◼ We shall now solve the problem with n= 2.


◼ Later we shall make use of it to solve the problem with n= 3.

18
Towers of Hanoi puzzle with 2 disks
The problem is to move two disks from first tower to the
third tower
The second tower is the temporary tower
Towers of Hanoi Puzzle

Step 1 Move n-1 disks source to temp


Towers of Hanoi Puzzle

Step 2 Move disk 1 from source to destination


Towers of Hanoi Puzzle

Step 3: Move disk from temp to destination


◼ So to move 2 disks , it required 3 steps in all
◼ It does not matter which tower is source and which is destination.

◼ Now let us extend the problem to 3 disks.


◼ We shall do it in 3 large steps
◼ Step 1: move 2 disks from source to temp (use destination T to do this)
◼ Step 2: Move the last remaining disk from source to destination
◼ Step 3: Move 2 disks from temp to destination (using source T to do this)

23
Towers of Hanoi with 3 disks
Let first tower be called a ( source tower)
Let third tower be called b ( destination tower)
Let second tower be called c ( temporary tower)
◼ n= 3
◼ Remove n-1 disks to temp tower
◼ We already know the solution to this problem
◼ We have just solved it in previous slides
◼ Let us simply copy the solution

25
Towers of Hanoi Puzzle

Step 1a
Start moving n-1 disks from source tower to temp
tower using destination tower
Towers of Hanoi Puzzle

Step 1 contd.
carry on process of moving n-1 disks from source
tower to temp tower using destination tower
Towers of Hanoi Puzzle

Step 1
We have completed moving n-1 disks from source to
temp using destination
We can go for step 2
Towers of Hanoi Puzzle

Step 2
It has only single operation.
Move remaining disk (disk 1) from source to
destination using temp ( It is just a single step)
◼ Step 3: Move n-1 disks (2 disks) from temp to destination using source
tower
◼ We already know how to move 2 disks from one tower to any other tower

30
Towers of Hanoi Puzzle

Step 3: Move n-1 disks (2 disks) from temp


to destination using source tower
Towers of Hanoi Puzzle
Towers of Hanoi Puzzle

Step 3:
We have now completed moving n-1 disks from
temp to destination using source tower
◼ In 3 major steps , we have solved the problem for n= 3 disks.

◼ We can now solve the problem for any value of n.


◼ The 3 steps remain the same for any size problem

34
Recursive Algorithm
void Hanoi( n, a, b, c) /*a :source, b:destination, c:temp*/
{
if (n == 1) /* base case */
Move( a, b);
else { /* recursion */
Hanoi( n–1, a, c, b); // a to c using b
Move( a, b); // last disk a to b
Hanoi( n–1, c, b, a); // c to b using a
}
}
Number of operations for Tower of Hanoi
◼ Although there are Three major steps, the number of actual operations will
depend on value of n.
◼ For n = 1, 1 step needed
◼ For n = 2, 1 + 1 + 1 (3 steps in 3 operations)
◼ For n = 3, 3 + 1 + 3 (3 steps in 7 operations)
◼ For n =4, 7 + 1 + 7 (15 operaions)
◼ ………….

36
Implementing Lists
- using arrays
- using Linked lists

38
• How many operations needed to carry out binary search for an
element in a sorted array containing 110,000 elements
Operations for Searching an Unsorted array
• If there are 1024 elements it would take max 1024 searches
• If there are 2048 elements it would take max 2048 searches

• If there are 1600 elements it would take max 1600 searches

40
Operations for Binary Search on a sorted
array
• Consider an array of size 8.
• Iteration 1: After checking mid element, array size reduced to 4.
• Iteration 2: array size reduced to 2.
• Iteration 3: array size reduced to 1.

• 2 3 =8

41
Binary Search in a sorted array with 16
• 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
• [ 108 121 237 288 332 370 460 482 515 555 578 626 747 874 930 995 ]
• Search for 125
• Iteration 1: (0+15)/2 = 7 :: 482 NO
• Iteration 2: (0+6)/2 = 3 :: 288 NO
• Iteration 3:(0+2)/2 = 1 :: 121 NO
• Iteration 4:(2+2)/2 = 2 :: 237 NO

• Any search would take max 4 operations.


• 2 4 = 16
• Taking log to base 2 4 log2 = log 16
• log 16 = 4

42
Operations for Searching a sorted array
• If there are 32 elements, 2 5 = 32
• it would take max 5 searches

10
• If there are 1024 elements, 2 = 1024
• Max 10 searches

• If there are 2048 elements 2 11 = 2048


• it would take max 11 searches

43
Operations for Searching a sorted array
• If there are 1600 elements

• 2 10 = 1024 and 2 11 = 2048


• it would take max 11 searches

• If there are 2000 elements?

44
Operations for Searching a sorted array
• If there are 1600 elements

• 2 10 = 1024 and 2 11 = 2048


• it would take max 11 searches

• If there are 2000 elements it would take max 11 searches

45
Operations for Searching a sorted array
• If there are 16000 elements
• How to solve this?

• We know that 1000 elements need 10 searches


• So split 16000 in two parts 16 x 1000
• 16000 = 16 x 1000 = 2 4 2 10
• it would take max 14 searches

46
Operations for Searching a sorted array
• If there are 32000 elements
• How to solve this?
• We know that 1000 elements need 10 searches
• So split 32000 in two parts 32 x 1000
• = 2 5 2 10
• it would take max 15 searches

47
Operations for Searching a sorted array
• If there are 25000 elements
• How to solve this?
• We know the solution to 16,000 and 32,000
• This number is between this range.
• So solution is the higher number (15)
• As search cannot be a fraction.

48
Operations for Searching a sorted array

• If there are 1 million elements


• 1000000 = 1000 x 1000 = 2 10 2 10

• it would take max 20 searches

49
• Given a sorted array of n elements what is the complexity of
searching for the largest element?
• Given an array of n elements

• [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18. . . . . . . 136]

What is the complexity of locating the missing element?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy