Sub topic 2
Binary Search and Its Recurrence
This chapter assumes you know loops, recursion, arrays, logarithms, and Big-O notation. It covers the sorting and searching algorithms in the plan, ending with heap sort.
Binary Search and Its Recurrence
Binary search finds a key in a sorted array by checking the middle element and discarding the half that cannot contain the key. Each step halves the range, so the recurrence is T(n) = T(n/2) + O(1). By the Master theorem (case 2, with a = 1, b = 2, d = 0), this gives O(log n) worst-case time. The best case is O(1), when the middle element is the key.
def binary_search(a, key):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == key:
return mid
if a[mid] < key:
lo = mid + 1
else:
hi = mid - 1
return -1Insertion, Selection, and Bubble Sort
These three sorts run in O(n²) worst-case time. Insertion sort is O(n) on already sorted input, so it is adaptive. Selection sort is O(n²) in every case. Bubble sort can stop early when a pass makes no swaps.
Stability, In-Place Sorting, and Adaptivity
A sort is stable when equal keys keep their original order. A sort is in-place when it needs only O(1) extra space. An adaptive sort runs faster on nearly sorted input. Insertion and bubble sort are stable, in-place, and adaptive. Selection sort is in-place but not stable in its usual form.
Merge Sort
Merge sort splits the array in half, sorts each half, and merges them. Its recurrence is T(n) = 2T(n/2) + Θ(n), which solves to Θ(n log n). It is stable but needs O(n) extra space.
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
out = []
i = j = 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
out.extend(left[i:])
out.extend(right[j:])
return outQuick Sort: Partitioning and Worst Case
Quick sort picks a pivot, partitions the array around it, and sorts each side. Its average time is Θ(n log n). If the pivot is always the smallest or largest element, the recurrence becomes T(n) = T(n-1) + Θ(n), which is Θ(n²). Quick sort is in-place but not stable.
Binary Heaps and Building a Heap in O(n)
A binary heap is a complete binary tree stored in an array. Node i has children at 2i + 1 and 2i + 2 (0-indexed). Building a heap by sifting down from the middle takes O(n) total, because most nodes sit near the bottom and do little work.
Heap Sort
Heap sort builds a max-heap in O(n), then repeatedly swaps the root to the end and restores the heap. Its time is Θ(n log n) in every case. It is in-place but not stable.
Exercise
Binary search on an array of 1,024 sorted items takes at most how many comparisons in the worst case?
Show answer
Each comparison halves the range, so at most log2(1024) + 1 = 11 comparisons.