Chapter 03
Searching & Sorting Algorithms
4 topics · 2 sections · beginner-friendly study notes · Updated
Binary search halves a sorted search space in O(log n); sorting algorithms trade time, space and stability: O(n^2) elementary sorts, O(n log n) merge sort (stable, O(n) space) and quick sort (in-place, O(n^2) worst case).
Sorting/searching is the most tested GATE algorithm topic; lower bound n log n and stability are recurring questions.
Database indexes, lower_bound queries, order statistics, external sorting of large files.
Binary Search Algorithm
Binary search finds a target in a sorted array by comparing with the middle element and discarding half each step: T(n)=T(n/2)+O(1)=O(log n). Requires random access and sorted order.
In short: Guess the middle; if too small look right, if too big look left.
Think about it
Appears in nearly every interview; the monotone-predicate generalization solves many optimization problems.
Use mid = l + (r - l)//2 to avoid integer overflow in fixed-width languages (l + r can overflow int32).
Loop invariant: if the target exists, it lies in [l, r].
Common bugs: infinite loop from mid=l with l=mid, using < vs <= in loop condition.
Lower bound = first index with a[i] >= x (insertion point); upper bound = first index with a[i] > x.
Count of x = upper - lower.
Search on answer space: if predicate feasible(x) is monotone (False..
False True..
True), binary search the minimum feasible x (capacity to ship packages in D days, Koko eating bananas, aggressive cows).
Rotated sorted array: one half is always sorted; decide which half contains the target.
Floating-point search iterates a fixed number of times instead of testing equality.
Worst case comparisons for n elements: floor(log2 n)+1.
Recursive version uses O(log n) stack; iterative O(1).
Key points
- Loop invariant: Condition true before each iteration which guarantees correctness.
- Lower bound: First position where element
>=x. - Monotone predicate: Once true stays true as x increases; enables answer-space search.
- Unsorted data: binary search is invalid; linear scan
O(n)or sort first. - Linked lists do not support
O(1)middle access, so binary search isO(n)there.
Read more
Example
CodeThree templates:
def binary_search(a, x):
l, r = 0, len(a) - 1
while l <= r:
m = l + (r - l) // 2
if a[m] == x: return m
if a[m] < x: l = m + 1
else: r = m - 1
return -1
def lower_bound(a, x): # first i with a[i] >= x
l, r = 0, len(a)
while l < r:
m = (l + r) // 2
if a[m] < x: l = m + 1
else: r = m
return l
def min_capacity(weights, days): # search on answer
def ok(cap):
d, cur = 1, 0
for w in weights:
if cur + w > cap: d += 1; cur = 0
cur += w
return d <= days
l, r = max(weights), sum(weights)
while l < r:
m = (l + r) // 2
if ok(m): r = m
else: l = m + 1
return lElementary Sorting Algorithms
Bubble sort repeatedly swaps adjacent out-of-order pairs; selection sort repeatedly selects the minimum of the unsorted part; insertion sort inserts each element into the sorted prefix. All are O(n^2) worst case and in-place (O(1) space).
In short: Simple quadratic sorts that are easy to code and good only for small or almost-sorted data.
Think about it
GATE regularly asks swaps/comparisons, stability and best-case behaviour of these sorts.
Bubble sort: n(n-1)/2 comparisons worst; with a swapped flag best case O(n) on sorted input; stable; swaps = number of inversions.
Selection sort: always n(n-1)/2 comparisons, at most n-1 swaps (minimum writes, useful when writes are costly); NOT stable in the swap form (e.
g.
[2a,2b,1] swaps 2a past 2b).
Insertion sort: best O(n) on sorted input, worst O(n^2) on reverse-sorted, average O(n^2); stable; adaptive; time = O(n + inversions); online.
Best for tiny n (< ~16-32) and nearly sorted data, so hybrids (Timsort, introsort) switch to insertion sort for small partitions.
Number of inversions in a reverse-sorted array of n: n(n-1)/2 (max).
Shell sort improves insertion sort via gap sequences (about O(n^1.5) or better).
Key points
- Stable sort: Equal keys keep their original relative order.
- Inversion: Pair i<j with a[i]>a[j]; insertion sort cost = n + inversions.
- Adaptive: Runs faster on partially sorted input.
- Stable: bubble, insertion, merge, counting, radix. Not stable (standard): selection, quick, heap.
- Comparison sorts have lower bound
Omega(n log n): decision tree has n! leaves, height>=log2(n!)=Theta(n log n).
Example
CodeBubble, selection, insertion:
def bubble(a):
n = len(a)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]; swapped = True
if not swapped: break
def selection(a):
n = len(a)
for i in range(n - 1):
m = i
for j in range(i + 1, n):
if a[j] < a[m]: m = j
a[i], a[m] = a[m], a[i]
def insertion(a):
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]; j -= 1
a[j + 1] = keyMerge Sort Algorithm
Merge sort splits the array in halves, sorts each recursively, and merges two sorted halves in linear time: T(n)=2T(n/2)+Theta(n)=Theta(n log n) in best, average and worst cases. Stable with O(n) auxiliary space for arrays.
In short: Split until single elements, then merge sorted pieces back together.
Think about it
The standard stable O(n log n) sort and the template for divide-and-conquer questions (inversions, counting smaller elements).
Merge step: two pointers compare heads and copy the smaller; use <= when taking from the left half to keep stability.
Always Theta(n log n) comparisons (between about (n log n)/2 and n log n - n + 1), recursion depth log n so stack O(log n) plus O(n) buffer.
Not in-place for arrays; for linked lists merge sort is O(1) extra space (excluding stack) and is the preferred sort.
Bottom-up merge sort avoids recursion.
Inversion counting: while merging, when an element from the right half is taken, add the remaining count of the left half; total O(n log n).
Excellent for external sorting (sequential access) and guaranteed worst-case.
Counting-comparison for merging sorted lists of sizes m and n: worst m+n-1.
Key points
- Merge: Combine two sorted sequences into one in
O(m+n). - Divide and conquer: Split, solve recursively, combine.
Read more
Example
CodeMerge sort with inversion count:
def merge_sort(a):
if len(a) <= 1: return a, 0
mid = len(a) // 2
L, x = merge_sort(a[:mid])
R, y = merge_sort(a[mid:])
out, i, j, inv = [], 0, 0, x + y
while i < len(L) and j < len(R):
if L[i] <= R[j]: # <= keeps stability
out.append(L[i]); i += 1
else:
out.append(R[j]); j += 1
inv += len(L) - i # inversions across halves
out += L[i:] + R[j:]
return out, invQuick Sort Algorithm
Quick sort picks a pivot, partitions so that smaller elements go left and larger go right, then recursively sorts both sides. Average O(n log n), worst O(n^2) when partitions are maximally unbalanced; in-place with O(log n) average stack; not stable.
In short: Choose a pivot, put smaller things before it and bigger after, repeat on each side.
Think about it
Most used practical sort; GATE loves its worst-case, partition tracing and quickselect.
Recurrence: T(n)=T(k)+T(n-k-1)+Theta(n).
Best/average: balanced splits give n log n (even a constant 1:9 ratio is still O(n log n)).
Worst: already sorted (or all equal) input with first/last pivot gives T(n)=T(n-1)+n=O(n^2).
Fixes: random pivot (expected O(n log n)), median-of-three, introsort (switch to heap sort when depth > 2 log n).
Lomuto partition: simple, pivot = last, O(n); Hoare partition: fewer swaps, two converging pointers.
Many equal keys need 3-way partition (Dutch flag) to avoid O(n^2).
Recurse on the smaller side and loop on the larger to bound stack at O(log n).
Quickselect finds the k-th smallest in expected O(n) (worst O(n^2); median-of-medians gives worst-case O(n)).
Quick sort beats merge sort in practice for arrays due to cache friendliness and no extra buffer.
Key points
Read more
Example
CodeRandomized quick sort and quickselect:
import random
def partition(a, lo, hi): # Lomuto
p = random.randint(lo, hi)
a[p], a[hi] = a[hi], a[p]
pivot, i = a[hi], lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]; i += 1
a[i], a[hi] = a[hi], a[i]
return i
def quick_sort(a, lo=0, hi=None):
if hi is None: hi = len(a) - 1
while lo < hi:
p = partition(a, lo, hi)
if p - lo < hi - p: # recurse on smaller side
quick_sort(a, lo, p - 1); lo = p + 1
else:
quick_sort(a, p + 1, hi); hi = p - 1
def quickselect(a, k): # k-th smallest, 0-indexed, expected O(n)
lo, hi = 0, len(a) - 1
while True:
p = partition(a, lo, hi)
if p == k: return a[p]
if p < k: lo = p + 1
else: hi = p - 1Solved examples
Number of comparisons in binary search worst case for n = 1000?
Comparisons
Formula Applied:—Approach note: Each comparison halves the range: 1000 -> 500 -> ... -> 1 takes ~10 halvings.
Count inversions in [3, 1, 2, 5, 4].
Inversion count
Formula Applied:—Approach note: Insertion sort swaps/shifts equal the inversion count.
Why is quick sort O(n^2) on an array of all equal elements with Lomuto partition, and how to fix it?
Explanation
Formula Applied:—Approach note: Random pivot alone does not help with all-equal keys.
How many swaps does selection sort perform on [4, 3, 2, 1] (n = 4) in the standard implementation that swaps once per outer pass?
Swap count
Formula Applied:—Approach note: Selection sort does O(n) swaps but O(n^2) comparisons.
Real-world applications
Using Searching & Sorting Algorithms in real projects
Database indexes, lower_bound queries, order statistics, external sorting of large files.
Common mistakes
❌ Myth: Quick sort is always O(n log n).
Why this is wrong: Bad pivots (sorted input with first/last pivot, all equal keys) give n^2.
✅ Verified Truth: Average/expected O(n log n); worst O(n^2). Randomization makes the bad case improbable.
⚠️ Exam Tip: GATE: "worst case of quick sort" -> O(n^2).
❌ Myth: Selection sort is stable.
Why this is wrong: The long-distance swap can jump an element over an equal one.
✅ Verified Truth: Standard selection sort is unstable; only a shifting variant is stable.
⚠️ Exam Tip: Stable list: bubble, insertion, merge, counting, radix.
❌ Myth: Binary search works on any array if you are careful.
Why this is wrong: It relies on order to discard half safely.
✅ Verified Truth: Sorted (or monotone predicate) is mandatory.
⚠️ Exam Tip: Check the precondition before applying.
Revision notes
Binary search halves a sorted search space in O(log n); sorting algorithms trade time, space and stability: O(n^2) elementary sorts, O(n log n) merge sort (stable, O(n) space) and quick sort (in-place, O(n^2) worst case).
High-Yield Quick Revision Points
- Binary search: mid = l + (r-l)//2; lower_bound; search on monotone answer
- Insertion O(n)/O(n^2), stable, adaptive; selection <= n-1 swaps, unstable
- Merge: Theta(n log n) always, O(n) space, stable; best for linked lists
- Quick: avg n log n, worst n^2, in-place, unstable; random pivot; 3-way for duplicates
- Comparison sort lower bound: Omega(n log n)
Practice questions
Best-case time of insertion sort is:
Which sort is NOT stable in its standard form?
Merge sort auxiliary space for arrays:
Quick sort with first-element pivot on sorted input takes:
Minimum number of swaps in selection sort for n elements is at most:
Lower bound for comparison-based sorting: