Algorithms
Sorting & Searching
Know every sort by its best/average/worst time, extra space, stability and in-place status, and recall the decision-tree lower bound — these properties drive nearly every sorting MCQ.
GATE CSE sorting and searching — linear and binary search, insertion, selection, bubble, merge, quick, heap, counting and radix sort, stability, in-place property and the comparison-sort lower bound.
Learning outcomes
- Quote best, average and worst time, space, stability and in-place status for each standard sort
- Count comparisons and swaps for insertion, selection and bubble sort on small inputs, including inversion-based reasoning
- Explain quick sort partitioning, bad pivots, and why balanced splits keep Θ(n log n)
- Use the decision-tree argument to justify the Ω(n log n) lower bound and know when counting/radix sort beat it
Searching: linear and binary search
- Linear search scans elements one by one: best Θ(1), worst Θ(n), works on unsorted data and linked lists.
- Binary search needs a SORTED array with O(1) random access. Compare the key with the middle element and discard half: T(n) = T(n/2) + 1, so T(n) = Θ(log n).
- Worst-case comparisons of binary search on n elements = ⌊log₂ n⌋ + 1 (successful or unsuccessful, counting one comparison per probe). For n = 1000 this is 10.
- Iterative binary search uses O(1) extra space; recursive uses O(log n) stack space.
- Binary search on a linked list gains nothing because reaching the middle costs Θ(n).
- Interpolation search guesses the position from key values: Θ(log log n) average on uniformly distributed data but Θ(n) worst case. Hashing gives expected Θ(1) search.
Formulas to remember
-
Binary search worst case = ⌊log₂ n⌋ + 1 probes -
T(n) = T(n/2) + 1 ⇒ Θ(log n)
Worked example
Problem. How many comparisons does binary search need in the worst case on a sorted array of 2^20 elements?
Solution. ⌊log₂ 2^20⌋ + 1 = 21 probes.
Elementary sorts: insertion, selection, bubble
- Insertion sort: insert a[i] into the sorted prefix by shifting larger elements right. Best Θ(n) on sorted input, worst Θ(n²) on reverse-sorted input. Number of swaps/shifts = number of INVERSIONS. Stable, in-place, adaptive, great for small or nearly sorted data.
- Selection sort: repeatedly select the minimum of the unsorted part. ALWAYS n(n−1)/2 comparisons in every case, but at most n − 1 swaps. In-place; the usual swap version is NOT stable.
- Bubble sort: repeatedly swap adjacent out-of-order pairs. With an early-exit flag the best case is n − 1 comparisons (already sorted); worst case n(n−1)/2 comparisons and swaps = inversions. Stable, in-place.
- Number of inversions in a permutation ranges from 0 (sorted) to n(n−1)/2 (reverse sorted). Any algorithm that swaps only adjacent elements needs at least (inversions) swaps.
- Average number of inversions in a random permutation is n(n−1)/4, so insertion and bubble sort are Θ(n²) on average.
Formulas to remember
-
Max inversions = n(n−1)/2 -
Selection sort comparisons = n(n−1)/2 (all cases) -
Insertion sort swaps = number of inversions
Worked example
Problem. Count the inversions in the sequence 3, 1, 4, 2. How many shifts does insertion sort perform?
Solution. Inverted pairs: (3,1), (3,2), (4,2) = 3 inversions, so insertion sort performs 3 shifts.
Merge sort and quick sort
- Merge sort: split into halves, sort each, merge. T(n) = 2T(n/2) + Θ(n) = Θ(n log n) in best, average and worst case. Needs Θ(n) auxiliary space for arrays, is stable, and is the preferred method for linked lists and external sorting.
- Merging two sorted lists of sizes m and n takes at most m + n − 1 comparisons (worst case) and min(m, n) comparisons in the best case.
- Quick sort: choose a pivot, partition so that smaller elements go left and larger right, recurse on both sides. Partition costs Θ(n).
- Quick sort best/average case: balanced splits, T(n) = 2T(n/2) + n = Θ(n log n). Worst case: pivot is always the min or max (e.g., sorted input with first/last-element pivot), T(n) = T(n−1) + n = Θ(n²).
- Even a constant-ratio split such as 1 : 9 gives T(n) = T(n/10) + T(9n/10) + n = Θ(n log n); only highly unbalanced splits (n−1 : 1) degrade quick sort.
- Quick sort is in-place (O(log n) average stack, O(n) worst) and NOT stable. Randomised or median-of-three pivots make the worst case unlikely, and Θ(n log n) worst case is possible with median-of-medians pivot selection.
Formulas to remember
-
Merge sort: T(n) = 2T(n/2) + n − 1 ⇒ Θ(n log n) -
Quick sort worst: T(n) = T(n−1) + n ⇒ Θ(n²) -
Quick sort best: T(n) = 2T(n/2) + n ⇒ Θ(n log n)
Worked example
Problem. What is the worst-case number of comparisons for merge sort on n = 8 elements using the standard merge?
Solution. M(n) = 2M(n/2) + n − 1 with M(1) = 0: M(2) = 1, M(4) = 5, M(8) = 17.
Heap sort, counting sort and radix sort
- Heap sort: build a max-heap bottom-up in Θ(n), then repeat n − 1 times: swap the root with the last element, shrink the heap, heapify in O(log n). Total Θ(n log n) in every case, in-place, NOT stable.
- Counting sort: for integer keys in 0..k, count frequencies, prefix-sum them, and place elements from right to left. Time Θ(n + k), space Θ(n + k), stable. Not comparison-based, so it beats Ω(n log n) when k = O(n).
- Radix sort: sort digit by digit (least significant first) with a STABLE sort per digit. For n numbers with d digits each in base b: Θ(d(n + b)). Needs the digit sort to be stable for correctness.
- Bucket sort: distribute into n buckets and sort each; Θ(n) expected when keys are uniform, Θ(n²) worst case.
- Counting sort on keys up to n² takes Θ(n²) — it is not helpful when the range k is much larger than n.
| Algorithm | Best | Average | Worst | Extra space | Stable | In-place |
|---|---|---|---|---|---|---|
| Insertion | n | n² | n² | 1 | Yes | Yes |
| Selection | n² | n² | n² | 1 | No | Yes |
| Bubble | n | n² | n² | 1 | Yes | Yes |
| Merge | n log n | n log n | n log n | n | Yes | No |
| Quick | n log n | n log n | n² | log n | No | Yes |
| Heap | n log n | n log n | n log n | 1 | No | Yes |
| Counting | n + k | n + k | n + k | n + k | Yes | No |
Worked example
Problem. Radix sort is applied to n = 1000 numbers of 4 decimal digits. How many stable counting-sort passes are done and what is the cost per pass?
Solution. d = 4 passes, each Θ(n + b) = Θ(1000 + 10), so about 4 × 1010 operations in total.
Lower bound for comparison sorting
- A comparison sort can be modelled as a binary decision tree whose leaves are the n! possible permutations. A binary tree with n! leaves has height at least ⌈log₂ n!⌉.
- Since log₂ n! = Θ(n log n), every comparison-based sort needs Ω(n log n) comparisons in the worst case; merge sort and heap sort are therefore asymptotically optimal.
- Minimum comparisons to sort 4 elements: ⌈log₂ 24⌉ = 5. For 3 elements: ⌈log₂ 6⌉ = 3. For 5 elements: ⌈log₂ 120⌉ = 7.
- Searching a sorted array by comparisons has lower bound ⌈log₂(n + 1)⌉, attained by binary search.
- Finding the maximum of n elements needs exactly n − 1 comparisons; finding both max and min needs ⌈3n/2⌉ − 2; the second smallest needs n + ⌈log₂ n⌉ − 2 in the worst case.
Formulas to remember
-
Height ≥ log₂(n!) = Θ(n log n) -
Max and min together: ⌈3n/2⌉ − 2 comparisons
Worked example
Problem. What is the minimum worst-case number of comparisons needed to sort 4 distinct elements?
Solution. 4! = 24 leaves, so height ≥ ⌈log₂ 24⌉ = ⌈4.58⌉ = 5.
GATE exam tricks — sorting properties
- Stable sorts (standard versions): insertion, bubble, merge, counting, radix. Unstable: selection, quick, heap. Remember with "I Bubble Merge Counting Radix are Stable".
- Already sorted input: insertion sort Θ(n); quick sort with first/last pivot Θ(n²); merge and heap sort Θ(n log n); selection sort Θ(n²).
- Reverse sorted input: insertion and bubble sort hit their worst case with n(n−1)/2 shifts or swaps.
- Linked list sorting: merge sort is natural (O(1) extra space for lists). Quick and heap sorts depend on random access.
- Number of swaps in selection sort ≤ n − 1; use it when writes are expensive.
- Inversion count tricks: swaps in bubble sort = inversions; each adjacent swap removes exactly one inversion.
- If keys are integers within O(n) range choose counting/radix for Θ(n); otherwise Θ(n log n) is optimal for comparison sorts.
- Merging k sorted lists of total n elements with a min-heap costs Θ(n log k).
Worked example
Problem. Quick sort uses the first element as pivot and is run on the sorted array 1, 2, …, n. What is its time?
Solution. The pivot is always the minimum, so splits are 0 : n−1, giving T(n) = T(n−1) + n = Θ(n²).
Exam tips
- Memorise the best/average/worst, space, stability and in-place table; most MCQs test exactly one cell.
- For numerical answers (comparisons, swaps) simulate on a tiny example and use inversions for insertion/bubble.
- Binary search comparisons = ⌊log₂ n⌋ + 1; selection sort comparisons = n(n−1)/2 always.
- Mention input order when evaluating quick sort — sorted input with a first-element pivot is the worst case.
- Counting and radix sort escape the Ω(n log n) bound because they are not comparison-based.
10 GATE-style MCQs for Sorting & Searching with full explanations. Attempt each question before revealing the answer.
What is the worst-case number of comparisons binary search makes on a sorted array of 1000 elements?
Show answer & explanation
Answer: B
⌊log₂ 1000⌋ + 1 = 9 + 1 = 10 probes, since 2^9 = 512 ≤ 1000 < 1024 = 2^10.
The running time of insertion sort on an already sorted array of n elements is:
Show answer & explanation
Answer: B
Each element is compared once with its predecessor and not shifted, giving n − 1 comparisons = Θ(n).
Quick sort that always picks the first element as pivot is applied to an already sorted array. The time is:
Show answer & explanation
Answer: C
The pivot is the smallest element every time, so splits are 0 : n−1 and T(n) = T(n−1) + Θ(n) = Θ(n²).
Which of the following sorting algorithms is stable (in its standard form)?
Show answer & explanation
Answer: C
Merge sort takes equal keys from the left sublist first, preserving relative order. Heap, selection and quick sort can reorder equal keys.
How many inversions does the array 3, 1, 4, 2 contain?
Show answer & explanation
Answer: B
Pairs (i < j) with a[i] > a[j]: (3,1), (3,2), (4,2) — 3 inversions.
What is the minimum number of comparisons needed in the worst case by any comparison-based algorithm to sort 4 distinct elements?
Show answer & explanation
Answer: B
The decision tree has 4! = 24 leaves, so its height is at least ⌈log₂ 24⌉ = 5 (as 2^4 = 16 < 24 ≤ 32 = 2^5).
Counting sort is used to sort n integers in the range 0 to k. Its time complexity is:
Show answer & explanation
Answer: B
One pass to count (n), one over the count array (k), and one to place (n): Θ(n + k).
The time to build a max-heap from n unordered elements with the bottom-up heapify method is:
Show answer & explanation
Answer: B
Work at height h is O(h) and there are about n/2^(h+1) nodes at that height, so Σ h·n/2^(h+1) = O(n).
Two sorted arrays of sizes m and n are merged into one sorted array. The maximum number of comparisons is:
Show answer & explanation
Answer: B
Each comparison places one element; the last element needs no comparison once one array is exhausted, giving at most m + n − 1.
Selection sort is applied to 6 distinct elements in any order. How many key comparisons does it make?
Show answer & explanation
Answer: C
Selection sort always makes (n−1) + (n−2) + … + 1 = n(n−1)/2 = 15 comparisons for n = 6, regardless of input order.
Extra page-specific practice beyond the GATE samples. Attempt all 10, then reveal answers to check your reasoning.
Bubble sort with an early-exit flag is run on an already sorted array of n elements. The number of comparisons is:
Show answer & explanation
Answer: A) n − 1
One pass makes n − 1 comparisons with no swap, so the flag stops the algorithm.
The worst-case time complexities of heap sort and quick sort (first-element pivot) are respectively:
Show answer & explanation
Answer: B) Θ(n log n), Θ(n²)
Heap sort is Θ(n log n) in all cases; quick sort degenerates to Θ(n²) with consistently bad pivots.
Which of the following sorting algorithms is both in-place and has Θ(n log n) worst-case time?
Show answer & explanation
Answer: C) Heap sort
Heap sort needs O(1) extra space and Θ(n log n) worst case. Merge sort needs Θ(n) extra space; quick sort is Θ(n²) worst case; counting sort is not in-place.
Quick sort always splits in the ratio 1 : 9. The time complexity is:
Show answer & explanation
Answer: B) Θ(n log n)
T(n) = T(n/10) + T(9n/10) + n has depth Θ(log n) with at most n work per level.
Radix sort sorts n numbers, each with d digits in base b. Its time complexity is:
Show answer & explanation
Answer: B) Θ(d(n + b))
There are d passes and each stable counting sort pass costs Θ(n + b).
The minimum number of comparisons needed to find the maximum of 8 distinct elements is:
Show answer & explanation
Answer: B) 7
Every non-maximum element must lose at least one comparison, so n − 1 = 7 comparisons are necessary (and sufficient).
The worst-case number of comparisons of binary search on a sorted array of 2^20 elements is:
Show answer & explanation
Answer: C) 21
⌊log₂ 2^20⌋ + 1 = 21.
The minimum number of comparisons needed to find both the maximum and minimum of 8 distinct elements is:
Show answer & explanation
Answer: B) 10
⌈3n/2⌉ − 2 = 12 − 2 = 10 by pairing elements.
Insertion sort is run on the reverse-sorted array 6, 5, 4, 3, 2, 1. The number of element shifts is:
Show answer & explanation
Answer: C) 15
Reverse-sorted array of 6 has 6·5/2 = 15 inversions, each requiring one shift.
Counting sort is used on n integers in the range 0 to n². Its time complexity is:
Show answer & explanation
Answer: C) Θ(n²)
Θ(n + k) with k = n² gives Θ(n²), which is worse than comparison sorts here.
Topic FAQs
Why is merge sort stable but heap sort not?
Merge sort takes the element from the left half on ties, preserving order; heap operations swap distant elements, so equal keys can change relative order.
When is insertion sort better than quick sort?
For small or nearly sorted inputs, where it runs in close to Θ(n) with very low overhead.
Is quick sort really in-place if it uses recursion?
Yes in the usual sense, since it needs no auxiliary array; only the recursion stack, O(log n) on average and O(n) worst case, is extra.
Can any sorting algorithm beat n log n?
Only non-comparison sorts such as counting, radix and bucket sort, by exploiting key structure; comparison sorts cannot.
Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.