Algorithms and programming Flashcards
What is a recursive algorithm?
A recursive algorithm is one that repeatably calls itself until a base case is met.
What are the advantages of recursion?
More natural to read.
Suited to certain problems, for example those using trees.
Quicker to write as some functions are naturally recursive.
Can reduce the size of the problem with each call
What are the disadvantages of recursion?
Can run out of stack space / memory (due to too many calls) causing it to crash. This can be avoided with tail recursion.
More difficult to trace / follow as each frame on the stack has its own set of variables
Requires more memory than the equivalent iterative algorithm.
Usually slower than iterative methods due to maintenance of the stack
What is iteration?
Iteration is when the same procedure is repeated using a count controlled ‘for’ loop or a condition controlled ‘while’ loop.
Identify where the recursion is taking place.
01 def factorial(n) 02 if n == 0: 03 return 1 04 else: 05 return n * factorial(n-1)
Line 05
Identify the base case/terminating condition.
01 def factorial(n) 02 if n == 0: 03 return 1 04 else: 05 return n * factorial(n-1)
Line 02
What is the worst case number of searches for binary search?
O(log2(n)) when the search reaches the deepest level of the tree.
What is the best case number of searches for binary search?
O(1) when the target value is the middle element.
What is the average case number of searches for binary search?
O(log2(n) -1)
What is the worst case number of searches for linear search?
O(n) when the value at the end of the list or not in the list so that n comparisons are needed.
What is the best case number of searches for linear search?
O(1) when the value is equal to the first element of the list so only one comparison is needed
What is the average case number of searches for linear search?
O(n/2)
What is logarithmic complexity O(log n)?
The inverse of exponential growth. (Halving a dataset)
What is linear complexity O(n)?
An algorithm who’s complexity will grow in direct proportion to the size of the input data. (For/While loop)
What is constant complexity O(1)?
Algorithm that will always execute in the same time regardless of the size of the input data set. (No loops)