Recursion Flashcards
Unary v Binary v n-ary Recursion
Unary - single recursive call is used
Binary - two recursive calls are used (so maybe go left & right)
n-ary - n recursive calls
Direct v Indirect recursion
Direct - recursive calls go to the same function
Indirect - recursion goes through two or more methods (p calls q, q calls p etc)
Tail recursion
Where the result of the recursive call is the result of the function
(so nothing is done on the way back)
Requirements for Recursion
- base case/s
- recursive call, where the result is combined
- convergance to the base case (so it becomes more simple each time)
Key Idea of Merge Sort
- Split the array into two halves
- Sort the smaller arrays
- Merge two sorted halves into a single sorted array
Trival split, complex merge
Merge Sort Psuedocode
Args: array, start, end, tmp array
if start != end:
- mid -> (start+end)//2
- recursive call (array, start, mid, tmp)
- recursive call (array, mid+1, end, tmp)
- call merge arrays (array, start, mid, end, tmp)
- copy array into temp from start to end - range(start, end+1)
Merge Arrays (Merge Sort) Psudeocode
ia -> start index
ib -> mid index + 1
for i in range(start, end+1):
- if ia > mid: (meaning half1 is finished, use half2)
set tmp[k] to a[ib]
ib += 1
- elif ib > end: (meaning half 2 is finished, use half1)
set tmp[k] to a[ia]
ia += 1
- elif a[ia] <= a[ib]:
tmp[k] = a[ia]
ia += 1
- else
tmp[k] = a[ib]
ib += 1
Quick Sort Psuedocode
Args: array, start, end
if start < end:
- boundary = partition(array, start, end)
- recursive_call(array, start, boundary-1)
- recursive_call(array, boundary+1, end)
complex split, no merge required
Partition (quick sort) psuedocode
Args: array, start, end
mid -> (start+end)//2
pivot -> array[mid]
swap(array, start, mid)
boundary -> start
for k in range(start+1, end+1):
- if array[k] < pivot:
- boundary += 1
- swap(array, k, boundary)
swap(array, start, boundary)
return boundary
Partition (quick sort) key idea
Pick a pivot (ideally the median)
move elements less than the pivot to the left, and greater than the pivot to the right
Quick Sort complexity
Best Case: O(n log(n))Comp - when pivot is median
Worst Case: O(n^2)compeq - when pivot is max/min
Merge Sort complexity
Best/Worst Case: O(n log(n))*Comp
Merge Sort v Quick Sort v other sorts
Merge Sort:
- better complexity, lower number of comparisons
- however, requires a temp array, so way more space is needed
Quick Sort:
- worse complexity
- but no need to copy back, so a lower constant if the pivot is good
Other sorts:
- both of these require recursion, so overhead is higher, and may not be worth it for smaller arrays