GATE CSE has asked 57 questions on Searching, Sorting & Selection (Algorithms) from 1991 to 2026, in 35 of the 46 papers; the most recent is in GATE CSE 2026 Set 2. In the last five years it carried 0.8 marks per 100-mark paper on average, against 1.3 since 2003. Since 2014 the questions have been 15 MCQ and 5 NAT. 7 groups of questions here are solved the same way; “One per method” keeps the newest of each.
Merge sort sorts [10,7,8,19,41,35,25,31] using its usual balanced contiguous halves and seven merges. A merge is void if its output is the sorted left half followed directly by the sorted right half. Count void merges.
Answer & solution
Official answer: 3
Step through it (9 steps)
Givens and goal
Merge sort sorts [10,7,8,19,41,35,25,31] using its usual balanced contiguous halves and seven merges. A merge is void if its output is the sorted left half followed directly by the sorted right half. Count void merges.
Approach
List all seven merges and test max(left)≤min(right).
Step-by-step solution
1. At the lowest level the pairs are [10] with [7], [8] with [19], [41] with [35], and [25] with [31]. The second and fourth are already in concatenated sorted order; the first and third are not. This level contributes two void merges. 2. The next left merge combines [7,10] and [8,19]. Since 10>8, their elements interleave and it is not void. The next right merge combines [35,41] and [25,31]; since 41>25, it is not void either. 3. At the root the sorted halves are [7,8,10,19] and [25,31,35,41]. Because 19<25, concatenating them is already sorted. The final merge is void. 4. The count is 2+0+1=3 among the 4+2+1=7 merges. Void means the resulting ordering needs no interleaving, not that the recursive subarrays were originally sorted or that the implementation necessarily skips its merge routine.
For i=0,…,n−2, an algorithm scans j=0,…,n−i−2 and swaps A[j],A[j+1] whenever A[j]>A[j+1]. Its input is 30 distinct integers in descending order. How many swaps occur?
Answer & solution
Official answer: 435
Approach: An adjacent out-of-order swap removes exactly one inversion, so count the input’s inversions. An inversion is a pair of positions i<j with A[i]>A[j]. In descending order every pair of distinct positions is an inversion. There are C(30,2)=30×29/2=435 such pairs. When two adjacent inverted values are swapped, their mutual inversion disappears. Their order relative to every other element contributes the same total as before, because no other element lies between the two positions. Thus each swap reduces the inversion count by exactly one. The shown bubble-sort passes finish in ascending order, with zero inversions, so exactly 435 swaps are required. A pass-by-pass check gives the same result: the largest value moves right in 29 swaps, the next in 28, and so on down to 1. Summing 29+28+⋯+1 gives 435. Comparisons and swaps are different quantities in general, even though every comparison succeeds for this descending distinct input.
An unordered list contains N distinct integers. In the comparison model, what is the minimum number of element comparisons needed to find any element that is not the largest? Assume N≥2. Options: A. 1; B. N−1; C. N; D. 2N−1.
Your answer
Answer & solution
Official answer: A
Compare any two distinct list elements, say a and b. If a<b, return a; otherwise return b. Because the keys are distinct, the returned key is strictly smaller than the other compared key, which also belongs to the list. This is already a certificate that the returned key is not the maximum of the entire list. We do not need to identify the maximum or inspect the other N−2 elements.
One comparison is sufficient and, in the worst-case comparison model, necessary. With zero comparisons there is no ordering evidence about the chosen element; arbitrary distinct input values could make it the largest. N−1 is the familiar bound for finding the actual maximum, which is a stronger problem. The assumption N≥2 is necessary: for N=1 no nonmaximum element exists. Answer: A.
An array A[1…n] has distinct elements and is bitonic: for some 1≤i≤n, A[1…i] is increasing and A[i+1…n] is decreasing. The boundary comparison is not specified. Find the best possible worst-case comparison bound for searching for a supplied key. Options: A. Θ(n); B. Θ(1); C. Θ((log n)²); D. Θ(log n).
Your answer
Answer & solution
Official answer: D
Distinctness makes the two monotone parts strict. At the partition boundary, if A[i]<A[i+1], the peak is i+1; otherwise it is i. Thus the array has a single peak, including the possible endpoint peaks of a purely increasing or decreasing array.
Find that peak with binary search on adjacent values. Maintain a candidate interval [lo,hi]. For mid<hi, if A[mid]<A[mid+1], the peak lies strictly to the right of mid; otherwise it lies at mid or to its left. Each comparison discards roughly half the interval, taking O(log n) comparisons. Then binary-search the increasing part in its normal order and the decreasing part with reversed comparison direction. Each search costs O(log n), so their sum, plus peak finding, remains O(log n), not O((log n)²).
For a lower bound, sorted arrays are included among bitonic arrays. In the comparison model, exact membership among n distinct ordered keys has n possible successful positions and requires Ω(log n) comparisons in the worst case. Therefore the attainable bound is Θ(log n): D.
An algorithm checks whether an N-element integer array is sorted in either ascending or descending order by one pass comparing adjacent elements. Its worst-case running time is: A both O(N) and Ω(N); B O(N) but not Ω(N); C Ω(N) but not O(N); D neither.
Your answer
Answer & solution
Official answer: A
Approach: Big-O and big-Omega describe upper and lower bounds on the same worst-case running-time function; they are not synonyms for worst case and best case. 1. Maintain whether any adjacent pair increases and whether any adjacent pair decreases. Each of the N−1 adjacent pairs requires only constant work. The single pass therefore takes at most cN+d operations, giving O(N). 2. On an already sorted array, no early contradiction occurs. The algorithm must examine through the final adjacent pair to certify the property. Such an input requires a number of comparisons proportional to N, giving a worst-case Ω(N) lower bound. 3. Together these bounds give Θ(N). Answer: A. Some unsorted inputs may allow early termination, but that does not remove the linear worst-case lower bound.
An array contains n integers. Let t be the optimal worst-case number of element comparisons needed to find both its minimum and maximum. Which printed bound is intended? A t>2n−2; B t>3⌈n/2⌉ and t≤2n−2; C t>n and t≤3⌈n/2⌉; D t>⌈log2 n⌉ and t≤n. The source gives no small-n restriction.
Your answer
Answer & solution
Official answer: C
Our answer: C for n≥5; small-n premise omitted
The optimal worst-case comparison count for simultaneous minimum and maximum is ceil(3n/2)−2. Compare elements in pairs, then compare each pair’s smaller element only against the running minimum and its larger element only against the running maximum; for even n this costs 3n/2−2, and for odd n it costs 3(n−1)/2. The standard adversary lower bound matches these counts. Consequently n<t≤3ceil(n/2) for n≥5, giving intended C. Literal qualification: for n=3 or 4, t=n, and for n=1 or 2 it is smaller, so the strict inequality in C is not valid for every unspecified n.
For even n, first compare one pair to initialize min/max (1 comparison); each of the remaining (n−2)/2 pairs needs one internal comparison and two comparisons with min/max. Total 1+3(n−2)/2=3n/2−2. For odd n, initialize both extrema to the first value for free, then spend three comparisons for each of (n−1)/2 pairs. Pseudocode for each pair (a,b): compare a,b; let lo=min(a,b), hi=max(a,b); compare lo with running_min and hi with running_max. For the matching lower bound, each nonmaximum needs a loss certificate and each nonminimum a win certificate, totaling 2n−2 certificates. An adversary classifies elements as untouched, winner-only, loser-only or both, and consistently places winner-only elements above loser-only elements. Comparing two untouched elements can create two certificates, but such comparisons are disjoint and number at most floor(n/2). Other comparisons can be answered to create at most one new certificate. Therefore at least 2n−2−floor(n/2)=ceil(3n/2)−2 comparisons are needed. This proof concerns worst-case comparisons, not a particular presorted input.
For [23,32,45,69,72,73,89,97], which standard sorting algorithm uses the fewest comparisons between array elements to sort in increasing order? A selection sort; B mergesort; C insertion sort; D quicksort with last-element pivot.
Your answer
Answer & solution
Official answer: C
Step through it (4 runs)
The displayed eight elements are already sorted. Standard insertion sort makes one failed element comparison for each of the seven later elements, totaling 7. Selection sort makes 28; ordinary mergesort makes more than 7; last-element-pivot quicksort repeatedly chooses the largest element and makes 28. Therefore insertion sort uses the least, C, for the standard versions of the named algorithms.
For selection sort the unsorted suffixes have lengths 8,7,...,2, producing 7+6+...+1=28 comparisons. Balanced top-down mergesort uses 4 comparisons merging singletons, 4 merging the sorted pairs, then 4 merging the two sorted halves, totaling 12 on this input. Insertion sort compares each new key with its immediate predecessor and stops, totaling 7. Quicksort's last pivot is always the maximum, so its partition costs sum to 28 in the standard implementation.
What is the worst-case number of arithmetic operations in recursive binary search on a sorted n-element array? A Θ(√n); B Θ(log₂ n); C Θ(n²); D Θ(n).
Your answer
Answer & solution
Official answer: B
Each binary-search call performs constant arithmetic and reduces the remaining interval by roughly one half. The worst-case recurrence is T(n)=T(n/2)+Θ(1), so Θ(log n), B, under the standard unit-cost arithmetic model.
After j unsuccessful comparisons, at most about n/2j candidates remain. Reaching one candidate needs j≈log₂n. A call computes a midpoint and adjusts bounds using a constant number of arithmetic operations. This counts operations, not bit complexity of arbitrary-precision index arithmetic.
Quicksort is applied to 25 distinct elements, choosing the first pivot uniformly among them. Find the probability that the first partition puts the pivot in a worst possible position, rounded to two decimal places.
Answer & solution
Official answer: 0.08
Method: characterize the pivot ranks that make the two recursive subproblems maximally unequal.
1. If the pivot has sorted rank r among 25 distinct elements, partitioning leaves r−1 elements smaller and 25−r larger. 2. The worst split is 0 and 24, leaving almost the entire problem for one recursive branch. This occurs when r=1 (minimum pivot) or r=25 (maximum pivot). 3. Exactly two of the 25 possible pivots have those ranks. Uniform selection makes each pivot equally likely, so the probability is 2/25=0.08.
Result: 0.08 to two decimal places. This asks only about the first split. It is not the probability that every later recursive call also takes its worst split, nor does a bad first pivot alone prove that the whole execution has the maximum possible running time.
There are n unsorted arrays, n odd, each containing n distinct elements; different arrays have no common elements. Find the worst-case complexity of computing the median of the n array medians. Choices A O(n), B O(n log n), C O(n²), D Ω(n² log n).
Your answer
Answer & solution
Official answer: C
1. The median of n distinct values for odd n is their order statistic of rank (n+1)/2. Finding that one rank does not require sorting every value. 2. Apply deterministic worst-case linear-time selection to each array. The median-of-medians selection algorithm, for example, finds an exact order statistic in O(n) time per array. 3. There are n arrays, so obtaining all their medians costs n×O(n)=O(n²). Store the n resulting medians in a separate array. 4. Apply linear-time selection once more to those n medians. This adds O(n), so the total remains O(n²), identifying C. The desired statistic is the median of array medians, which is not in general the median of all n² input values. 5. Sorting each original array would cost O(n² log n) and is unnecessary. Worst-case exact selection on arbitrary unsorted rows requires inspecting linearly many entries in potentially decisive rows; the general problem has quadratic worst-case scale, not O(n) or O(n log n) in the row count n. Randomized quickselect offers expected linear selection, but deterministic selection is what directly justifies the worst-case bound here.
An array of 31 entries consists of zeros followed by ones. Find the smallest index i with A[i]=1 using the minimum number of array probes. What is an optimal algorithm’s worst-case probe count?
Answer & solution
Official answer: 5.0
Our answer: 5
1. A probe returns one bit: if A[mid]=0 the first one lies to the right; if A[mid]=1 it lies at mid or to the left. This monotonicity permits binary search.
2. Balanced probing halves the candidate boundary positions each time. Five probes suffice for 31 first-one positions, or 32 possibilities if an all-zero sentinel is allowed.
3. For optimality, a binary decision tree of depth four has at most 24=16 leaves, fewer than 31 distinguishable answers. Thus no algorithm can guarantee four probes. The optimal worst case is 5, not a linear scan of 31.
Select the worst-case running times of insertion sort, merge sort, and quicksort, in that order. A: Θ(n log n), Θ(n log n), Θ(n^2). B: Θ(n^2), Θ(n^2), Θ(n log n). C: Θ(n^2), Θ(n log n), Θ(n log n). D: Θ(n^2), Θ(n log n), Θ(n^2).
Your answer
Answer & solution
Official answer: D
Insertion sort may shift Θ(n) elements on each of n insertions, giving Θ(n²). Merge sort uses Θ(n) work across each of Θ(log n) levels, giving Θ(n log n). Quicksort’s most unbalanced partitions give n+(n−1)+...+1=Θ(n²). Thus D.
For reverse-sorted input, insertion sort shifts 1+2+...+(n−1) elements. Merge sort's balanced divide-and-conquer recurrence T(n)=2T(n/2)+Θ(n) yields Θ(n log n) regardless of initial order. Quicksort can repeatedly choose an extreme pivot, leaving subproblems of sizes 0 and n−1, so its recurrence becomes T(n)=T(n−1)+Θ(n). Its average-case or expected randomized Θ(n log n) bound must not be substituted for this requested worst-case bound.
For ascending sorted input, assess: I quicksort is Θ(n²); II bubblesort is Θ(n²); III mergesort is Θ(n); IV insertion sort is Θ(n). A I,II only; B I,III only; C II,IV only; D I,IV only. The source supplies no implementation details.
Your answer
Answer & solution
Official answer: D
Our answer: D under textbook implementation conventions
With first/last-element pivot selection, sorted input gives quicksort Θ(n²). An early-exit bubble sort detects no swaps after one pass and takes Θ(n), ordinary mergesort remains Θ(n log n), and insertion sort takes Θ(n). These conventions make I and IV true, D. The names alone do not determine these cases: a balanced/randomized-pivot quicksort need not be quadratic, unoptimized bubble sort can be quadratic, and adaptive mergesort can be linear. The official answer requires the stated implementation choices.
The quadratic quicksort recurrence is T(n)=T(n−1)+Θ(n), whose level costs add to Θ(n²). The insertion-sort best case makes one failed comparison per new item, hence linear work. Standard merging processes n elements at each of log n levels. These derivations explain the official convention rather than falsely treating algorithm names as complete implementations.
For n≥2, choose the worst-case quicksort recurrence; c is constant. A T(n)=2T(n/2)+cn; B T(n)=T(n−1)+T(1)+cn; C T(n)=2T(n−1)+cn; D T(n)=T(n/2)+cn.
Your answer
Answer & solution
Official answer: B
Worst-case pivots repeatedly leave one side with nearly every remaining element. Treat the constant-size side's cost as O(1), yielding T(n)=T(n−1)+Θ(n). Unrolling accumulates n+(n−1)+…+2=Θ(n²). A represents balanced splitting, C duplicates the large subproblem, and D omits one half of a balanced sort. Printed B uses T(1) for constant work.
Solution: The most unbalanced quicksort split leaves one nontrivial subproblem of size n−1 and constant base-case work, plus cn partition work. Hence the listed recurrence T(n)=T(n−1)+T(1)+cn, B, gives Θ(n²).
An unordered list has n distinct elements. What is the asymptotic number of comparisons needed to find an element that is neither maximum nor minimum? AΘ(nlogn), BΘ(n), CΘ(logn), DΘ(1), assuming n≥3.
Your answer
Answer & solution
Official answer: D
Assuming n≥3, inspect any three distinct elements and return their median using at most three comparisons. It has a smaller and larger element within those three, so cannot be the global minimum or maximum. A constant positive number of comparisons suffices and is necessary, Θ(1), D.
Choose any three distinct list elements and compare them to identify their middle value. That value is larger than one chosen element and smaller than another, so it cannot be an extreme of the full list. This uses at most three comparisons regardless of n. At least some information is needed to certify a nonextreme value on arbitrary unsorted data, so the asymptotic requirement is constant. For n<3 no such value exists, which is why that natural premise is stated.
partition(a, n)moves first-element pivot to end of left part and prose says it returns left part COUNT. Skeleton sets p=partition(a, n); if(p+1==k)return a[p]; if(p+1>k)return kth_smallest(…); else return kth_smallest(…). Missing calls: A(a, p, k), (a+p+1, n−p−1, k−p−1); B(a, p, k), (a, n−p−1, k−p−1); C reverse A calls; D(a, n−p−1, k−p−1), (a, p, k). The fixed code instead requires pivot INDEX.
Your answer
Answer & solution
Official answer: A
Our answer: A only if partition returns zero-based pivot index
With pivot index p, its rank is p+1. The left recursive call uses(a, p, k); the right uses(a+p+1, n−p−1, k−p−1), giving A. However the prose explicitly says partition returns the left-part COUNT, which is p+1. The fixed skeleton then compares the wrong rank and accesses the wrong element; no option repairs that. Correct by assigning left_end=partition(a, n)−1 or changing the function contract to return the pivot index. Official A retains this index interpretation.
If p were the zero-based pivot index, its rank would be p+1. Recursing left keeps the same base pointer and k but changes length to p. Recursing right advances past the pivot byp+1 and subtracts that many elements from both length and rank. These are A’s arguments. But the prose-returned count is p+1 already; assigning it to p makes the fixed equality and a[p] off by one before either missing call runs. Thus no choice repairs the literal contract. A applies only after changing the contract or subtracting 1 on assignment.
A mergesort implementation takes 30 seconds in the worst case for an input of size 64. Using its standard asymptotic running-time model, which option most closely approximates the maximum input size solvable in 6 minutes? (A) 256; (B) 512; (C) 1024; (D) 2048.
Your answer
Answer & solution
Official answer: B
1. Using the standard dominant-term model T(n)=c n log₂n, the time increases by 360/30=12.
2. Hence n log₂n≈12·64·6=4608. For n=512, 512·9=4608, so B. Lower-order implementation overhead is ignored in this approximation.
Quicksort sorts ascending using the first element as pivot. Let t₁ be its comparison count on [1,2,3,4,5] and t₂ the count on [4,1,5,3,2]. Which holds? A: t₁=5. B: t₁<t₂. C: t₁>t₂. D: t₁=t₂. Use the conventional partitioning comparison model.
Your answer
Answer & solution
Official answer: C
Our answer: C under standard linear partition comparisons
Step through it (2 runs)
1. Method and setup. With the first-element pivot, an already sorted list always selects the smallest remaining value, producing maximally unbalanced recursive subproblems. For the second list, pivot 4 separates three smaller elements from one larger element. Bounding the cost of sorting that three-element side suffices; its exact partition order is unnecessary.
2. Work through the result and its assumptions. Sorted input with first-element pivot repeatedly splits 0 versus n−1, using 4+3+2+1=10 pivot comparisons. The second input first splits 3 versus 1, so its total is 4 plus at most 3 within the three-element side, at most 7. Thus t1>t2, C. This is the usual partition comparison model, not arbitrary redundant implementation tests.
What is the minimum worst-case number of comparisons needed to find both the minimum and maximum of 100 numbers?
Answer & solution
Official answer: 147.1 to 148.1
Our answer: 148 worst-case comparisons
1. Method and setup. Finding extrema separately takes 99+99 comparisons and wastes information. Pair the elements: one comparison per pair identifies a candidate for the minimum and a candidate for the maximum. Thereafter only the pair-losers need participate in the minimum search and only the pair-winners in the maximum search.
2. Work through the result and its assumptions. Compare50 disjoint pairs. Find the minimum among 50 smaller values in 49 comparisons and maximum among 50 larger values in 49. Total 50+49+49=148. This matches the optimal worst-case lower bound ceil(3n/2)−2; an adversary forces enough first comparisons to classify candidates before eliminating all but one in each class.
Quicksort on n elements always selects the element at the central array index as pivot. What is the tightest listed worst-case upper bound? A O(n²); B O(n log n); C Θ(n log n); D O(n³).
Your answer
Answer & solution
Official answer: A
Step 1: A central position in an array is not necessarily the median value. An adversarial ordering can place the smallest or largest current value at each selected pivot position. Step 2: Partitioning then leaves subproblems of sizes 0 and n−1 while doing Θ(n) work. The recurrence is T(n)=T(n−1)+Θ(n). Step 3: Summing the partition costs gives Θ(n+(n−1)+…+1)=Θ(n²). Therefore A is the tightest offered upper bound; O(n³) is true but weaker.
Similar questions2 more → · asked again: GATE 2009, Q11
Selection-sort swap count
Searching, Sorting & Selection
Tap to enlarge
Give the tightest listed upper bound on selection-sort swaps for n numbers: A O(log n), B O(n), C O(n log n), D O(n²).
Your answer
Answer & solution
Official answer: B
Each selection-sort pass finds the minimum of the unsorted suffix and moves it using at most one swap. There are n−1 passes, and worst-case inputs require a linear number of swaps. Hence O(n), B; the quadratic comparison count does not imply quadratic swaps.
On pass i, selection sort scans the remaining suffix to locate its minimum, then swaps it into position i. It may perform many comparisons during that scan, but at most one swap. There are n−1 such passes, giving at most n−1 swaps. A cyclic displacement input can require a swap on each pass, so the worst-case number grows linearly, not logarithmically. The commonly remembered quadratic selection-sort cost counts comparisons, not swaps.
How many elements can heapsort sort in Θ(log n) time? AΘ(1), BΘ(√log n), CΘ(log n/log log n), DΘ(log n).
Your answer
Answer & solution
Official answer: C
Let m be the number of elements. Heapsort takes Θ(m log m). Choosing m=Θ(log n/log log n) gives log m=Θ(log log n), so m log m=Θ(log n). Hence C; m=Θ(log n) would require an extra log log n factor.
Use a new variable m for the input length, since n only describes the time budget. Heapsort costs Θ(m log m). Set L=log n. The candidate m=L/log L has log m=log L−log log L=Θ(log L), so m log m=Θ(L). Constant m is too small, and m=√L gives Θ(√L log L)=o(L). Setting m=L instead gives Θ(L log L), which is too large. Thus the inverse scale is log n/log log n.
A list of n strings, each of length n, is sorted lexicographically using mergesort. What is the worst-case running time? (A) O(n log n) (B) O(n² log n) (C) O(n²+log n) (D) O(n²).
Your answer
Answer & solution
Official answer: Marks to All
Our answer: B under the standard character-comparison model
Ordinary mergesort uses O(n log n) comparisons to sort n strings. A lexicographic comparison can inspect all n characters, so the standard upper bound is O(n² log n), option B. The bound is tight in the usual character-by-character implementation: strings can share a prefix of length n−O(log n) and have suitably ordered distinct suffixes, so a worst-case merge pattern performs Θ(n log n) comparisons each costing Θ(n). Treating entire strings as unit-cost keys, using LCP-aware comparison, or restricting how many distinct strings exist changes the analysis; those are extra models not specified. The official entry remains Marks to All. No official reason for awarding marks is asserted.
Check: At each merge level O(n) string comparisons may be needed, and there are Θ(log n) levels. Multiplying by the worst-case Θ(n) character work per comparison gives Θ(n² log n) under the ordinary implementation, rather than counting comparisons as constant-time operations.
Similar questions2 more → · asked again: GATE 2013, Q6
Selection-sort worst-case swaps
Searching, Sorting & Selection
Tap to enlarge
What is the worst-case number of swaps in selection sort on n elements? A Θ(n); B Θ(n log n); C Θ(n²); D Θ(n² log n).
Your answer
Answer & solution
Answer: A (no official key was published)
Each pass places one selected minimum using at most one swap, and there are n−1 passes. Inputs exist requiring a linear number of those swaps, so the worst-case swap count is Θ(n), A, despite Θ(n²) comparisons.
Selection sort scans the remaining suffix to find its minimum and moves that minimum into the next position. There are n−1 such placements and at most one swap per placement. Some inputs require a swap in a linear number of passes, giving a tight Θ(n) worst-case swap count. This differs from its Θ(n²) comparison count, since each pass may examine many elements before performing only one exchange.
Quicksort selects the n/4-th smallest key as pivot using a linear-time selection algorithm. What is its worst-case time? A Θ(n); B Θ(n log n); C Θ(n²); D Θ(n² log n).
Your answer
Answer & solution
Answer: B (no official key was published)
Selecting the one-quarter order statistic in linear time gives recurrence T(n)=T(n/4)+T(3n/4−1)+Θ(n). Each recursion level has linear total work, and the longest/shortest nontrivial paths are logarithmic up to constants. Equivalently the Akra–Bazzi exponent is 1 because 1/4+3/4=1. Thus Θ(n log n), B, assuming rank partitioning is implemented appropriately for distinct keys or duplicates.
At each partition, linear-time selection plus partitioning costs Θ(n), and subproblems have sizes approximately n/4 and 3n/4. Both are fixed fractions, so recursion depth is Θ(log n); total size across a complete level remains proportional to n until leaves. Consequently total cost is Θ(n log n). Choosing the quarter-rank pivot is not perfectly balanced, but still prevents the n−1 versus 0 split responsible for quadratic quicksort.
What is the minimum worst-case number of comparisons needed to determine whether some integer appears more than n/2 times in a sorted array of n integers?
(A) Θ(n) (B) Θ(log n) (C) Θ(log* n) (D) Θ(1)
Your answer
Answer & solution
Answer: B (no official key was published)
1. If a value occurs more than n/2 times, it must occupy the middle array position. Take that value as candidate and use binary searches for its first and last occurrences; accept exactly when the count exceeds n/2. 2. This needs Θ(log n) comparisons in the worst case. A logarithmic lower bound follows by locating a candidate-block boundary among linearly many possible positions while distinguishing length floor(n/2) from floor(n/2)+1. 3. Sortedness is essential; without it a linear majority scan is needed. Thus B.
A quicksort pivot procedure splits the list into two sublists each containing at least n/5 elements. If T(n) counts sorting comparisons, which offered upper recurrence follows?
1. Each recursive subproblem has size at most 4n/5, because each side has at least n/5 elements. With the usual monotone worst-case upper-bound interpretation of T and linear partitioning cost, both recursive costs are bounded individually by T(4n/5), so T(n)≤2T(4n/5)+n, option C. 2. This loose recurrence follows immediately from the given size bounds. The tempting expression T(n/5)+T(4n/5)+n assumes that the most unequal permitted split maximizes the sum of recursive costs; monotonicity alone does not establish that. 3. More precisely the general recurrence is T(n)≤maxn/5≤k≤4n/5{T(k)+T(n−k)}+O(n), ignoring pivot/rounding constants. The standard comparison model includes linear partition/pivot overhead; the statement does not specify the cost of an arbitrary extra pivot-selection procedure.
Which listed sorting algorithm has the lowest worst-case time complexity? Options: (A) Merge sort (B) Bubble sort (C) Quick sort (D) Selection sort
Your answer
Answer & solution
Answer: A (no official key was published)
1. Approach. Compare guaranteed worst-case bounds, not average performance. Mergesort halves the input and performs linear merging on each recursion level.
2. Derivation and interpretation. Standard mergesort guarantees Θ(n log n) worst-case time. Bubble sort, selection sort and conventional quicksort can take Θ(n²) in the worst case. Hence mergesort, A.
Given an array of an even number n of values, both its minimum and maximum must be found. Which comparison-count claim is true? Options: (A) At least 2n−c comparisons are necessary for some constant c (B) At most 1.5n−2 comparisons are sufficient (C) At least n log₂ n comparisons are necessary (D) None of these
Your answer
Answer & solution
Answer: B (no official key was published)
1. Approach. A comparison within a pair simultaneously rules one element out as maximum and the other out as minimum. Exploit this dual use before separately reducing the two candidate sets.
2. Derivation and interpretation. Partition the even number n of values into n/2 pairs. Compare within each pair, putting its smaller member in a minimum-candidate set and larger member in a maximum-candidate set. Find the minimum of the n/2 smaller values and maximum of the n/2 larger values. The comparison count is n/2+(n/2−1)+(n/2−1)=3n/2−2, so B. This construction disproves the claimed asymptotically larger lower bounds in A and C.
Among the standard in-place sorting algorithms listed, which needs the fewest swaps under the conventional worst-case exchange-count comparison? Options: (A) Quicksort (B) Insertion sort (C) Selection sort (D) Heapsort
Your answer
Answer & solution
Answer: C under the standard swap-based comparison (no official key was published)
1. Selection sort places the minimum remaining item in its final location with at most one exchange per pass, hence at most n−1 swaps. Standard swap-based insertion sort, quicksort and heapsort can use more.
2. Thus selection sort, C, in the conventional worst-case exchange-count comparison. A shift-based insertion implementation can avoid an explicit swap operation, so literal source-code swap counts are implementation-dependent.
3. Teaching check: Selection sort can inspect the entire unsorted suffix without moving any item, then exchange its minimum with the first unsorted position. This separates comparison count, Θ(n²), from exchange count, O(n). The question asks about swaps, not fastest running time.
The median of n elements can be selected in O(n) time. What is quicksort’s complexity if the median is always chosen as pivot, with balanced partitioning? Options: (A) Θ(n) (B) Θ(n log n) (C) Θ(n²) (D) Θ(n³)
Your answer
Answer & solution
Answer: B (no official key was published)
1. Select the median in Θ(n) time and partition in Θ(n) time, producing two subproblems of approximately n/2 elements. The recurrence T(n)=2T(n/2)+Θ(n) gives Θ(n log n), option B, including the median-selection cost.
2. This assumes standard balanced handling of duplicate keys or distinct keys; a two-way partition that mishandles equal keys can defeat that guarantee.
3. Teaching check: Finding the median is not free, but its linear cost can be absorbed into the same Θ(n) term as partitioning. Each recursion level processes a total of Θ(n) elements, and balanced halves give Θ(log n) levels. Thus median selection does not make quicksort linear overall.
Merge roughly log n sorted lists, each containing roughly n/log n elements, using a heap. Options include A O(n log log n), B Θ(n log n), C Ω(n log n), D Ω(n^(3/2)). Find the intended efficient merge bound.
Your answer
Answer & solution
Answer: A (no official key was published)
Keep the smallest remaining item from each of k=Θ(log n) lists in a min-heap. Repeatedly extract the minimum and replace it by the next item from the same list. There are Θ(n) items, each costing O(log k)=O(log log n), so the merge costs O(n log log n), A. The comparison lower bound for arbitrary interleavings of equally sized lists is Ω(n log k), so this is also the worst-case asymptotic order.
The heap needs one current head per list, only Θ(log n) elements. Removing the smallest head and inserting its successor costs O(log log n), not O(log n), because heap height depends on list count. Repeating for Θ(n) output elements gives O(n log log n). The lists are already internally sorted, so sorting their whole union from scratch would waste that available order.
What is the tight asymptotic order of the worst-case lower bound on comparisons required by comparison-based sorting of n elements? Options: (A) n (B) n² (C) n log n (D) n(log n)²
Your answer
Answer & solution
Answer: C (no official key was published)
1. A comparison decision tree must distinguish n! possible input permutations, so its worst-case height is at least ceil(log2(n!))=Ω(n log n). Mergesort or heapsort attains O(n log n), making that the tight order of the worst-case comparison bound, C.
2. Teaching check: A binary comparison tree of height h has at most 2h leaves. Distinct orderings need separate leaves, so 2h≥n!. Summing logarithms or using Stirling’s estimate gives log2(n!)=Θ(n log n). This lower bound applies to comparison sorting, not every integer-key sorting method.
Array insertion sort normally uses linear search to find where the next element belongs. If binary search replaces that search, what happens to worst-case total running time? A. It remains Θ(n²); B. It becomes Θ(n(log n)²); C. It becomes Θ(n log n); D. It becomes Θ(n).
Your answer
Answer & solution
Answer: A (no official key was published)
1. During insertion into a sorted prefix of length i, search needs O(log i) comparisons but opening an array slot may move i elements. Summing these movements over all prefixes dominates the sum of logarithmic searches. Binary search improves comparisons, not the cost of physically maintaining the sorted array.
2. Binary search reduces comparisons needed to locate each insertion position, but array elements still must shift to make room. A reverse-sorted input needs 1+2+...+(n−1)=Θ(n²) moves. The worst-case runtime therefore remains Θ(n²), A, despite O(n log n) comparisons.
For a permutation a1,...,an of n distinct integers, an inversion is an index pair i<j with ai>aj. What is insertion sort's worst-case time if inputs are restricted to permutations of 1,...,n with at most n inversions? A. Θ(n²) B. Θ(n log n) C. Θ(n^1.5) D. Θ(n)
Your answer
Answer & solution
Answer: D (no official key was published)
1. In insertion sort, a larger element shifts right exactly when it is an inversion partner of the current key. Each original inversion causes one such shift and is then removed. 2. With I inversions, the inner loops therefore make I shifts. The n−1 outer iterations and their final failed/boundary tests add Θ(n) work, so total work is Θ(n+I). 3. The restriction I≤n gives O(n+n)=O(n). Reading and processing n entries still requires Ω(n), including an already sorted input. 4. Matching the upper and lower bounds gives Θ(n), D. The unrestricted reverse-order example has Θ(n²) inversions and is excluded here.
Solution: In standard insertion sort, shifting an earlier larger element past the current key removes exactly one inversion. Total shifts equal the input inversion count I, and outer-loop work plus terminating comparisons contributes Θ(n). Hence running time is Θ(n+I). With I≤n this is O(n), while scanning the n elements requires Ω(n), so the restricted worst case is Θ(n), option D.
An unsorted array A[1..n] contains n distinct values and contains x. A search repeatedly chooses i uniformly from 1..n, compares A[i] with x, stops on equality, and otherwise repeats the random choice. What is its expected comparison count before stopping? (A) n; (B) n−1; (C) 2n; (D) n/2.
Your answer
Answer & solution
Answer: A (no official key was published)
Step 1: Recognize independent repeated trials.
Step 2: After any failed draw, the algorithm restarts with the same success probability 1/n; it has not removed that position from future draws. Thus the comparison count is geometric, P(N=k)=(1−1/n)k−1/n. Its mean is 1/(1/n)=n, agreeing with the recurrence E=1+(1−1/n)E.
Conclusion: Each independently sampled index hits the unique target with probability 1/n. If E is the expected number of comparisons including the successful comparison, E=1+(1−1/n)E, giving E=n, A. Resampling already examined positions is allowed; this is not a random permutation scan.
Quicksort selects each pivot randomly. What is its worst-case sorting complexity on n values: O(n), O(n log n), O(n²), or O(n!)?
Your answer
Answer & solution
Answer: C (no official key was published)
Step 1: Random pivot selection improves the expected split quality, but it does not make extreme pivots impossible. A sequence selecting the minimum or maximum at every partition still has nonzero probability.
Step 2: That sequence performs(n−1)+(n−2)+…+1=n(n−1)/2 partition comparisons, yielding Θ(n²).
Thus C is the tight worst-case bound. Θ(n log n) is the expected runtime over the random choices, not the maximum possible runtime of a particular execution.
A sorted array s contains n integers. Determine whether two distinct elements sum to less than 1000. What is the most efficient asymptotic runtime, including choice O(1)?
Your answer
Answer & solution
Answer: A (no official key was published)
Step 1: In ascending order, the smallest sum of two distinct positions is s[1]+s[2]. Every other pair replaces one or both elements by values at least as large.
Step 2: If that sum is below 1000, a qualifying pair exists; otherwise no pair can qualify. Only two accesses, an addition, and a comparison are needed.
Thus Θ(1), option A, for n≥2 with random-access storage. For n<2 return false immediately. Searching all pairs or applying a two-pointer scan is unnecessary for this inequality-existence question.
An array has four 0s, five 1s and three 2s, and is to be sorted increasingly using swaps. GFG Q64 p9 permits nonadjacent swaps; GateForum Q17 p16 requires adjacent swaps. Solve both distinct source versions. Find the maximum, over initial orders, of the minimum required swaps.
Answer & solution
Answer: 7 for arbitrary swaps; 47 for adjacent-only swaps. (no official key was published)
Arbitrary-swap version: partition the target positions into zones of sizes 4,5,3 for 0,1,2. A misplaced value j in zone i is a directed edge i→j. Incoming and outgoing edge counts balance at every zone. First cancel every opposite pair i→j,j→i with one swap, fixing two positions. Once opposite pairs are exhausted, remaining edges form consistently oriented 3-cycles, each fixed by two swaps. Let d be the number of canceled pairs and c the number of remaining 3-cycles. This uses d+2c swaps and moves M=2d+3c<=12 misplaced positions. Each 3-cycle uses one position in the 2-zone, so c<=3. For c=0,1,2,3, the bound d<=floor((12−3c)/2) gives d+2c<=6,6,7,7 respectively. Hence seven swaps always suffice. Attainment: use 1111|00222|001, where bars show target zones. Its opposite pairs are two 0/1 pairs and one 1/2 pair, and the remaining six misplaced entries form two 3-cycles, so seven suffice. To see six cannot suffice, all 12 positions are initially wrong. Six swaps would have to fix two positions each, and thus every swap would need to exchange an opposite pair without creating any new error. There are only three opposite pairs initially; after removing those, the remaining directed 3-cycles have no such pair. Six swaps are therefore impossible. The worst-case optimum is exactly 7. Adjacent-only version: the minimum number of swaps equals the inversion count because an adjacent swap changes that count by exactly 1, and swapping adjacent inverted pairs sorts while decreasing it each time. The largest inversion count is attained by descending groups 222111110000. Every unequal pair is then inverted: 3*5+3*4+5*4=15+12+20=47. Equal-value pairs contribute zero. This discrepancy is substantive; the paper is authenticated as the official wording.
An array has four 0s, five 1s and three 2s, and is to be sorted increasingly using swaps. GFG Q64 p9 permits nonadjacent swaps; GateForum Q17 p16 requires adjacent swaps. Solve both distinct source versions. Give an order attaining the worst-case minimum.
Answer & solution
Answer: Arbitrary: 111100222001. Adjacent-only: 222111110000. (no official key was published)
For arbitrary swaps, choose [1,1,1,1 | 0,0,2,2,2 | 0,0,1], with target-zone lengths 4,5,3. The counts are four 0s, five 1s, three 2s. Number positions 1 through 12. One seven-swap sorting sequence is (1,5),(2,6),(7,12),(3,10),(8,10),(4,11),(9,11). After the first three swaps, the unsorted portion consists of two cycles, each carrying a 1 in the 0-zone, a 2 in the 1-zone and a 0 in the 2-zone. Each takes two swaps. All 12 entries were initially misplaced, so six swaps would require every swap to fix two errors. Only three opposite pairs are available, and a residual 3-cycle cannot be fixed in that way. Thus seven are necessary as well as sufficient; the general upper bound is proved in part(a). For adjacent-only swaps, choose [2,2,2,1,1,1,1,1,0,0,0,0]. It has 3*5 inversions of type(2,1), 3*4 of type(2,0), and 5*4 of type(1,0), for 47. No array with these multiplicities can have more inversions, because every unequal pair is already inverted here. An adjacent inversion-removal sort takes exactly 47 swaps. This descending arrangement is not the arbitrary-swap witness: allowing distant exchanges changes the optimization problem.
Does stable sorting mean O(n log n) time, preservation of the order of equal keys, divide-and-conquer, or O(n) space?
Your answer
Answer & solution
Answer: B (no official key was published)
Label two records with equal key as (k,first) and (k,second), in that input order. A stable sort guarantees that first still precedes second afterward. That property matters when one field has already been sorted and a later stable pass sorts another field. Runtime, extra space and algorithmic paradigm are separate properties: a stable insertion sort may take quadratic time, while some fast sorts are unstable. Hence the definition is B.
Partition n array values so negatives precede positives. What is the minimum number of arbitrary exchanges in the worst case: n−1,n,n+1,or none?
Your answer
Answer & solution
Answer: D: floor(n/2) (no official key was published)
Suppose there are k negative values. Their final region is the first k positions. Let t positives currently lie in that region; exactly t negatives then lie outside it. Pair and swap each misplaced positive with a misplaced negative, requiring t exchanges. Every exchange fixes at most one misplaced negative in the target region, proving optimality. Since t≤min(k,n−k), the worst case over k is floor(n/2), attained by placing balanced sign groups in the wrong halves. Thus none of the listed formulas A–C is the general answer. This uses arbitrary swaps, not adjacent swaps.
Sort 20,47,15,8,9,4,40,30,12,17 by straight two-way merging. What is the order after the second pass?
Your answer
Answer & solution
Answer: B: 8,15,20,47,4,9,30,40,12,17 (no official key was published)
Step through it (10 steps)
Pass one merges singleton runs into pairs: [20,47], [8,15], [4,9], [30,40], [12,17]. Pass two merges adjacent pairs into four-element sorted runs. The first two yield [8,15,20,47]; the next two yield [4,9,30,40]. The final pair has no partner and remains [12,17]. Concatenating these runs gives B. The whole array is not yet sorted; later passes merge the length-four runs and the remaining tail.
An n×n matrix A has every row and column in ascending order. Draw a decision tree finding its first, second, and third smallest entries using the minimum number of comparisons. Assume n≥2; count repeated values as separate entries.
Shared context
An n×n matrix A has every row and column in ascending order. Draw a decision tree finding its first, second, and third smallest entries using the minimum number of comparisons. Assume n≥2; count repeated values as separate entries.
Answer & solution
Answer: Two comparisons suffice and are necessary in the worst case. (no official key was published)
The first entry is always A₁₁. Set b=A₁₂ and c=A₂₁. Every remaining entry is at least b or c, so the second is min(b,c).
If b≤c, the only candidates for third are c and d=A₁₃. Other entries in the first row are at least d; entries outside the first row are at least c (including A₂₂). If c<b, the analogous candidates are b and e=A₃₁. When n=2, the missing d or e can be treated as +∞, so the third is simply the other one of b,c and just one comparison suffices for that special size.
For n≥3 the full decision tree is:
compare b ≤ c?
/ yes \ no
compare d ≤ c? compare e ≤ b?
/ yes \ no / yes \ no
(A₁₁,b,d) (A₁₁,b,c) (A₁₁,c,e) (A₁₁,c,b)
Each root-to-leaf path has two comparisons. The leaves give the first three entries in order. Ties can follow the ≤ branch: tied entries have equal values, so either identity order is valid.
Optimality for n≥3: all four strict order possibilities displayed at the leaves can occur in a row-and-column-sorted matrix. A single binary comparison has only two outcomes and cannot distinguish four possible ordered triples of positions; two comparisons are necessary in the worst case. For n=2 there are only the two orders of b,c and one comparison is both sufficient and necessary. For n=1 a third entry does not exist, so the task presupposes at least n=2.
Match log n, n, n log n, n² to binary search, selection, merge sort, insertion sort.
Your answer
Answer & solution
Answer: B: 3, 1, 4, 2 (no official key was published)
Binary search halves a sorted interval each step, giving logarithmic search time. Selection of a specified rank can be done in linear worst-case time using median-of-medians. Merge sort has logarithmically many levels with linear work per level, giving n log n. Insertion sort can shift a quadratic number of elements on reverse-sorted input. Therefore the intended mapping is 3, 1, 4, 2, B. “Selection” means order-statistic selection, not selection sort, whose worst-case comparisons are quadratic.
A sought item is equally likely to occupy any of n positions in a sequentially searched list. Find the expected comparisons for a successful search.
Your answer
Answer & solution
Answer: D: (n+1)/2 (no official key was published)
If the item occupies position i, searching from the beginning requires i comparisons. Uniform success positions therefore give E[C]=(1+2+…+n)/n. The arithmetic-series sum is n(n+1)/2, so E[C]=(n+1)/2. This is not the unsuccessful-search cost n, because successful searches stop at their target. Nor is it a binary-search logarithm, since the stated algorithm scans sequentially rather than repeatedly halving a sorted range.
Compare quicksort comparisons for a list already ascending versus descending when no pivot or partition implementation is specified.
Your answer
Answer & solution
Answer: D in general; C for standard end-pivot worst-case counting (no official key was published)
With the first or last element chosen as pivot on every subarray, either monotone input can split into sizes 0 and n−1. Counting n−1 comparisons per partition gives n(n−1)/2 for both orientations, the usual equality answer C under that model. But the question does not specify pivot selection or partition code. A rule depending on input orientation can select balanced pivots in one case and extreme pivots in the other; even comparison-count conventions vary. Therefore no implementation-independent ordering follows, corresponding to D. The common equal-count result is conditional, not a universal theorem about every quicksort variant.
How many comparisons asymptotically suffice to merge sorted lists of sizes m and n into one sorted list?
Your answer
Answer & solution
Answer: C: O(m+n) (no official key was published)
Compare the two current front items, emit the smaller and advance that list. Every comparison emits one item, and once one list is exhausted the remaining items can be copied without further comparisons. At most m+n−1 comparisons are therefore needed when both lists are nonempty. Balanced interleavings can attain this bound, giving linear worst-case work. Merely searching in logarithmic time would not output the entire merged list; the standard merge exploits the existing order of both inputs.
Evaluate I more hash entries increase collisions; II recursive programs are efficient; III quicksort worst case O(n²); IV binary search on a linear linked list is efficient.
Your answer
Answer & solution
Answer: D: I and III under the usual fixed-table expected-collision interpretation (no official key was published)
Quicksort can repeatedly split off only one pivot, giving (n−1)+(n−2)+…+1=Θ(n²), so III holds. In a fixed-size table under uniform hashing, adding keys increases expected collision pressure, supporting I in the conventional sense. Recursion alone guarantees no efficiency bound, and a linked list lacks constant-time midpoint access, so II and IV are not general truths. Strictly, a particular inserted key can land in an empty bucket without adding a collision; “increases” in I is an expected trend or nondecreasing count, not a guaranteed strict increase at every insertion.
Use the usual left-to-right version: compare adjacent entries and swap whenever the left entry exceeds the right. After one full pass, the largest element of the active prefix has bubbled to its final rightmost position. Shorten the active prefix by one for the next pass.
Pass 1: 37,52,12,11,25,92. Pass 2: 37,12,11,25,52,92. Pass 3: 12,11,25,37,52,92. Pass 4: 11,12,25,37,52,92. Pass 5: 11,12,25,37,52,92. For example, in pass 1, 92 is successively swapped with 37,52,12,11,25. In pass 2, 52 moves to the penultimate position. A no-swap early-exit implementation would detect completion on pass 5 in this trace.
The source does not specify pass direction. The equally valid right-to-left version bubbles minima left and gives: [11,92,37,52,12,25], [11,12,92,37,52,25], [11,12,25,92,37,52], [11,12,25,37,92,52], [11,12,25,37,52,92]. Both reach the same sorted list; intermediate pass answers depend on the convention.
Which recurrence models worst-case binary search: T(n)=T(n/2)+k, 2T(n/2)+k, T(n/2)+log n, or T(n/2)+n?
Your answer
Answer & solution
Answer: A (no official key was published)
A binary-search step compares the target with the middle key and discards one half. Only the surviving half is searched recursively, so there is one T(n/2) term, not two. Selecting and comparing the middle item takes constant time in an indexed array, represented by k. Repeated halving reaches a constant-size range after Θ(log n) steps. The recurrence presupposes constant-time midpoint access; a linked-list implementation has different access costs.
An integer array satisfies A[1]≤A[2]≤…≤A[n]. Give Pascal-like linear-time pseudocode to find indices i,j with A[i]+A[j]=M if a pair exists. State how equal indices are treated.
Answer & solution
Answer: Start i=1,j=n; advance i if sum<M, decrease j if sum>M, return at equality. Use i<j for distinct indices, i≤j if reuse is allowed. (no official key was published)
For distinct array positions, use: i:=1; j:=n; found:=false; while (i<j) and not found do begin s:=A[i]+A[j]; if s=M then found:=true else if s<M then i:=i+1 else j:=j−1 end; if found then output(i,j) else output('no pair'). A return statement at equality is an equivalent formulation. Use an arithmetic type wide enough to avoid overflow in the sum.
The invariant is that any still-possible pair lies entirely within the index interval [i,j]. If A[i]+A[j]<M, then A[i]+A[k]≤A[i]+A[j]<M for every k≤j in that interval. Therefore no candidate using i works, and discarding i is safe. If the sum exceeds M, then A[k]+A[j]≥A[i]+A[j]>M for all remaining k≥i, so discarding j is safe. Equality supplies a valid witness immediately. These arguments use nondecreasing order and therefore also cover duplicates and negative integers.
Each unsuccessful iteration shortens the interval by one; there are at most n−1 such iterations, giving O(n) time and O(1) auxiliary space. Empty and single-element arrays have no distinct-position pair.
The source does not explicitly require i≠j. If reusing a single position is permitted, change the loop condition to i≤j. The same elimination proof then includes the diagonal pair when 2A[i]=M. Keeping this variant explicit prevents silently rejecting a valid pair under that interpretation.
The printed procedure loops i=1 to n−1, tests A[i]>A[i+1], swaps adjacent entries if true, and then unconditionally calls bubblesort(n−1). It has no base-case guard and prints temp : A[i] instead of a valid assignment. Let an count executions of the if test. Give a recurrence and solve it.
Answer & solution
Answer: With base case a1=0, an=a(n−1)+n−1, giving n(n−1)/2 comparisons (the printed recurrence has no base case) (no official key was published)
First distinguish the literal source from its conventional intended algorithm. As printed, the procedure has no terminating case and contains a malformed temp assignment. It is not a valid terminating Pascal sort. After correcting assignment punctuation and adding a guard such as "if n<=1 then return", the standard comparison-count question is well-defined.
For the repaired algorithm, one call on n>=2 performs exactly n−1 tests A[i]>A[i+1], irrespective of the data or whether the consequent swap executes. It then calls the procedure once on n−1. Therefore a1=0 and an=a(n−1)+(n−1), n>=2. Equivalently a0=0 may be used with the guard. Repeated substitution gives an=(n−1)+(n−2)+...+1+a1=n(n−1)/2. An induction verifies the closed form: it is 0 at n=1; if a(n−1)=(n−1)(n−2)/2, adding n−1 yields n(n−1)/2. Thus the comparison count and running time are Theta(n2), even for sorted input, because there is no early-exit flag. The swaps, unlike tests, depend on data: zero for sorted input, up to n(n−1)/2 for reverse order with distinct entries.
A complete repaired algorithm is:
procedure bubblesort(A,n):
if n<=1: return
for i=1,...,n-1:
if A[i]>A[i+1]:
temp:=A[i]
A[i]:=A[i+1]
A[i+1]:=temp
bubblesort(A,n-1)
Each pass moves the largest of the first n entries to position n; recursion sorts the preceding prefix. Without the added guard the recursive calls proceed through n=1,0,−1,... (or fail because of the index type/stack), so the printed code does not successfully finish. The finite formula is explicitly for the repaired intended algorithm, not a claim that the literal program terminates.
Which listed method sorts n integers in [1, n³] in O(n): heapsort, quicksort, mergesort, radix sort?
Select all that apply
Answer & solution
Answer: D: radix sort (no official key was published)
Subtract one to put keys in [0, n³−1], then represent each in base n using three digits. Stable counting sort of one digit takes O(n+n)=O(n) time and O(n) auxiliary storage, so three least-significant-digit passes remain linear. Comparison sorts retain their general Ω(n log n) worst-case comparison barrier on arbitrary distinct keys; the integer representation lets radix sorting escape that model. The bound assumes word operations and digit extraction on these O(log n)-bit keys take constant time.
Quicksort always uses the final element as pivot. Give a worst-case permutation of distinct keys 1, …, n.
Answer & solution
Answer: Ascending order 1, 2, …, n under the standard partition implementation (no official key was published)
On ascending input, the last pivot is the maximum. Partitioning places every other element on one side, creating subproblem sizes n−1 and 0. If the standard partition preserves the ascending order of that remaining region, the same imbalance repeats. Comparisons sum to (n−1)+(n−2)+…+1=n(n−1)/2, which is Θ(n²). Reverse order is another common worst-case input. The statement concerns ordinary end-pivot partitioning, not a modified algorithm that deliberately rearranges or selects pivots differently after inspecting the data.
What minimum number of comparisons suffices to sort five arbitrary distinct keys?
Answer & solution
Answer: 7 in the optimal worst case (no official key was published)
There are 5!=120 possible strict orders, and a binary comparison tree of height six distinguishes at most 64 outcomes. Thus at least seven comparisons are necessary in the worst case. For sufficiency, sort two pairs (two comparisons), compare their larger elements (one), and rename them so a≤b≤d with c≤d. Insert the fifth key into a, b, d in at most two comparisons. Insert c into the prefix preceding d: at most three elements precede d, giving at most four possible positions and two further comparisons. Total: seven. This is a worst-case guarantee; a best-case successful path can be shorter.
Give an optimal comparison-based algorithm, with pseudocode and analysis, to sort n numbers containing k distinct values; k is not known in advance.
Answer & solution
Answer: Use a balanced search tree of distinct values and counts, then inorder expansion: O(n log(k+1)) time and O(k) auxiliary space; worst-case optimal in the comparison model. (no official key was published)
Maintain one node per distinct key in a balanced binary search tree, storing a frequency counter. Unlike a simple unbalanced BST, an AVL or red-black tree guarantees height O(log(d+1)) when d distinct values have been encountered. The algorithm discovers k automatically.
SORT_FEW_DISTINCT(A):
T := empty balanced search tree
for x in A:
node := FIND(T,x)
if node exists: node.count := node.count + 1
else: INSERT_BALANCED(T, key=x, count=1)
output := empty sequence
for node in INORDER(T):
repeat node.count times: append node.key to output
return output
After each insertion, the tree contains exactly the distinct input values seen so far, with their correct multiplicities. Inorder traversal visits keys in increasing order, and expanding each count preserves all occurrences. Thus the output is a sorted permutation of the input.
Each of n updates costs O(log(k+1)); inorder traversal costs O(k), and emitting n values costs O(n). Total time is O(n log(k+1)), commonly written O(n log k) for k≥2. The +1 handles k=1, where the algorithm is linear. Auxiliary tree storage is O(k), excluding the n-element output; an array can be overwritten during the final traversal if the input need not be retained.
For worst-case comparison optimality at fixed n and k, consider balanced multiplicities among k ordered values. There are n!/(n1!…nk!) distinguishable orderings, where each ni is approximately n/k. A constant-branching comparison decision tree requires Ω(log(n!/(n1!…nk!)))=Ω(n log k) comparisons in the worst case for k≥2. Reading or writing the input/output also costs Ω(n), giving Ω(n log(k+1)) overall. This is a worst-case statement over multiplicities, not a claim of distribution-sensitive optimality for every frequency pattern. With bounded integer keys, counting/radix methods may bypass the comparison lower bound; without a key-universe assumption they are not a general replacement.