

















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


















Data Structures & Algorithms Recursion Anum Tariq, Lecturer Department of Software Engineering Mirpur University of Science and Technology (MUST)
▫ (^) either through recursion or ▫ (^) through iteration.
Recursive and Iterative Implementations of Factorial Algorithm Recursive Algorithm: Fact(n) if (n = 1) return 1 else return n * Fact(n-1) Iterative Algorithm: Fact(n) Factorial = 1 while (n >= 1) Factorial = n * Factorial n=n- End-while return Factorial Input: A non-negative number n Output: Value of n!
By Recursion By Looping int Factorial(int n) { if (n==0) // base case return 1; else return n*Factorial(n-1); } int Factorial(int n) { int fact = 1; for(int count=2; count<=n; count+ +) fact = fact * count; return fact; } 07/19/ Recursion
▫ (^) Example: Fibonacci number sequence, factorial function, quick sort and more. Some of the algorithms/functions can be represented in an iterative way and some may not.
Recursive Thinking: The General Approach
Requirements for Recursive Solution
Characteristics of Recursive Methods
Recursive algorithm for finding length of a string: public static int length(String str) { if (str == null || str.equals(“”)) return 0; else return length(str.substring(1)) + 1; } Recursion 07/19/
Recursion 07/19/