Intermediate·1 min read
Recursion & Divide and Conquer
Master recursive thinking with Towers of Hanoi, Merge Sort, and Quick Sort.
Recursion & Divide and Conquer
Recursion is a function that calls itself on smaller subproblems until reaching a base case.
Anatomy of Recursion
``python
def recurse(n):
if n <= 0: # Base case - stops recursion
return
recurse(n - 1) # Recursive call on smaller input
``Towers of Hanoi
Move n disks from source → destination using an auxiliary peg.
Rules: Only move one disk at a time. Never place a larger disk on a smaller one. Solution: Move n-1 disks to auxiliary, move largest to destination, move n-1 from auxiliary to destination. Recurrence: T(n) = 2T(n-1) + 1 → O(2ⁿ)Merge Sort (Divide and Conquer)
- Divide: Split array in half
- Conquer: Recursively sort each half
- Combine: Merge sorted halves
Quick Sort
- Partition: Pick pivot, place it in correct position
- Conquer: Recursively sort left and right partitions
Code Example
python
def tower_of_hanoi(n, source='A', target='C', auxiliary='B'):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n - 1, source, auxiliary, target)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n - 1, auxiliary, target, source)
print("Towers of Hanoi (3 disks):")
tower_of_hanoi(3)
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i]); i += 1
else:
result.append(right[j]); j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
data = [38, 27, 43, 3, 9, 82, 10]
print("Merge:", merge_sort(data.copy()))
print("Quick:", quick_sort(data.copy()))Practice Problems
- 01Solve Tower of Hanoi and print the sequence of moves
- 02Implement merge sort to sort a linked list
- 03Use quicksort's partition logic to find the kth largest element