Skip to main content
Albero Academy

Recursion, Sorting & Searching

Solve problems by breaking them down — recursion, binary search, the classic sorts, and a first look at trees.

Chapter 4DSA17 min readBeginner friendly
  • #DSA
  • #Recursion
  • #Sorting

Recursion — a function that calls itself on a smaller input — is the mental model behind searching, sorting and trees. This final chapter ties the course together: recursion, the O(log n) power of binary search, how the fast sorts work, and a first look at trees.

Recursion

Every recursion needs a base case (when to stop) and a recursive case (shrink toward the base):

recursion basics
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case
# Same shape solves many "divide and conquer" problems
def sum_list(items):
if not items: return 0
return items[0] + sum_list(items[1:])

Binary search

On a sorted array, binary search halves the search space each step — O(log n). A million items takes about 20 steps:

binary search
def binary_search(nums, target): # nums is sorted
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target: return mid
if nums[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1

Sorting

In practice you call the built-in sort (O(n log n)). But knowing how the fast ones work is standard interview material:

SortAverageIdea
Bubble / InsertionO(n²)Simple, fine for tiny/nearly-sorted data
Merge sortO(n log n)Split in half, sort each, merge (stable)
Quick sortO(n log n)Partition around a pivot, recurse
merge sort — divide & conquer
def merge_sort(a):
if len(a) <= 1: return a
mid = len(a) // 2
left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
# merge two sorted halves
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: out.append(left[i]); i += 1
else: out.append(right[j]); j += 1
return out + left[i:] + right[j:]

A first look at trees

A tree is a branching structure — each node has children. A binary tree has at most two. Traversing one is naturally recursive, and a binary search tree keeps values ordered for O(log n) lookup:

recursive tree traversal
def inorder(node):
if not node: return
inorder(node.left)
print(node.val)
inorder(node.right)

Practice

Implement factorial and a recursive list sum, binary search on a sorted array, and merge sort. Then write an in-order traversal of a small binary tree. You've now covered the DSA toolkit that most interviews draw from.

Key takeaways

  1. 01Recursion needs a base case and a recursive case that shrinks toward it — or it overflows.
  2. 02Binary search halves a sorted array each step: O(log n).
  3. 03Merge and quick sort are O(n log n); bubble/insertion are O(n²) — know how they work.
  4. 04Trees are branching structures traversed recursively; BSTs give O(log n) lookup.
  5. 05Big-O, arrays/hash maps, linked structures, recursion & sorting/searching cover most interviews.