Back to the 2023 paper

Module 2: Fundamental Algorithmic Strategies

20239m

Write the step-by-step process of Quick Sort using an example. Write the advantages and disadvantages of Quick Sort compared to other sorting algorithms, such as Merge Sort and Bubble Sort.

Worked SolutionAI Assisted

Quick Sort Step-by-Step + Pros/Cons vs Other Sorts

Step-by-Step Example A=[38,27,43,3,9,82,10]A=[38,27,43,3,9,82,10], pivot last element

  1. Partition [38,27,43,3,9,82,10] pivot10 → i scan → final swapped → [3,9,10,38,27,82,43] pivot index2
  2. Left [3,9] pivot9 → already [3,9]
  3. Right [38,27,82,43] pivot43 → partition → [38,27,43,82] → left [38,27] pivot27→[27,38] , right [82]
    Sorted [3,9,10,27,38,43,82]

If using Hoare with median-of-three pivot choice, fewer worst cases.

Algorithm (as in Q14)

QuickSort(A,l,h): if l<h: p=Partition(A,l,h); QuickSort(A,l,p-1); QuickSort(A,p+1,h)

Complexities (see Q14): Best/avg Θ(nlog⁡n)\Theta(n\log n), worst Θ(n2)\Theta(n^2).

Advantages

  • In-place, low constants, cache-friendly → fastest in practice on arrays.
  • Average O(nlog⁡n)O(n\log n), tail recursion can be bounded to O(log⁡n)O(\log n) stack.
  • Good for large datasets, easily parallelizable.

Disadvantages

  • Not stable (equal elements may reorder).
  • Worst O(n2)O(n^2) on sorted/duplicate input if naive pivot (mitigated by randomized/median pivot).
  • Not good for linked lists (needs random access; Merge Sort better).
  • Recursion depth risk stack overflow on worst case.

Comparison

Sort Avg Worst Space Stable In-place
Quick Sort nlog⁡nn\log n n2n^2 log⁡n\log n No Yes
Merge Sort nlog⁡nn\log n nlog⁡nn\log n nn Yes No
Heap Sort nlog⁡nn\log n nlog⁡nn\log n 1 No Yes
Insertion n2n^2 avg n2n^2 1 Yes Yes

Conclusion: Use Quick Sort (randomized) for arrays when average speed matters; Merge Sort when stability or guaranteed nlog⁡nn\log n needed.

Similar questions

Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.