CSC325 ยท 2079 ยท 5 marks
Trace the quick sort algorithm for sorting the array A[] = 15, 7, 6, 23, 18, 34, 25 and write its best and worst complexity.
Trace the quick sort algorithm for sorting the array $A[] = {15, 7, 6, 23, 18, 34, 25}$ and write its best and worst complexity. [5]
Quick Sort - Trace, Best and Worst Complexity
Given
- Array to sort: $A[] = {15, 7, 6, 23, 18, 34, 25}$, indices $0$ to $6$
- $n = 7$ elements
- Required: trace Quick Sort, and best and worst case time complexity
- Pivot rule not specified. I use the first element as pivot (standard TU convention, Lomuto/Hoare style).
Solution
I use the Hoare-style partition with pivot = first element.
Initial: pivot = 15, range [0..6]
15 7 6 23 18 34 25
0 1 2 3 4 5 6
- $i$ from left moves right while $A[i] < 15$: $A[1]=7<15$, $A[2]=6<15$, $A[3]=23\ge15$ โ stop at $i=3$.
- $j$ from right moves left while $A[j] > 15$: $A[6]=25>15$, $A[5]=34>15$, $A[4]=18>15$, $A[3]=23>15$, $A[2]=6\le15$ โ stop at $j=2$.
- $i > j$, so swap pivot $A[0]$ with $A[j]=A[2]$:
$${6, 7, \mathbf{15}, 23, 18, 34, 25}$$
Pivot 15 now at index 2. Left part = ${6,7}$, right part = ${23,18,34,25}$.
Left sub-array {6, 7}, pivot = 6, range [0..1]
- $i$: $A[1]=7\ge6$ โ stop at $i=1$.
- $j$: $A[1]=7>6$ โ move to $j=0$.
- $i>j$, swap pivot $A[0]$ with $A[0]$ โ no change.
$${\mathbf{6}, 7}$$
Pivot 6 at index 0; right part ${7}$ single element, sorted.
Right sub-array {23, 18, 34, 25}, pivot = 23, range [3..6]
23 18 34 25
3 4 5 6
- $i$: $A[4]=18<23$, $A[5]=34\ge23$ โ stop at $i=5$.
- $j$: $A[6]=25>23$, $A[5]=34>23$, $A[4]=18\le23$ โ stop at $j=4$.
- $i>j$, swap pivot $A[3]$ with $A[4]$:
$${18, \mathbf{23}, 34, 25}$$
Pivot 23 at index 4. Left part ${18}$ sorted; right part ${34,25}$.
Sub-array {34, 25}, pivot = 34, range [5..6]
- $i$: $A[6]=25<34$ โ $i$ goes past range, stop at $i=6$ (or beyond).
- $j$: $A[6]=25\le34$ โ stop at $j=6$.
- $i \ge j$, swap pivot $A[5]$ with $A[6]$:
$${25, \mathbf{34}}$$
Final Sorted Array
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Value | 6 | 7 | 15 | 18 | 23 | 25 | 34 |
$$A[] = {6, 7, 15, 18, 23, 25, 34}$$
Time Complexity
Best Case: $O(n \log n)$
- Pivot splits the array into two nearly equal halves each time.
- Recurrence: $T(n) = 2T(n/2) + O(n)$
- Solution: $T(n) = O(n \log n)$
Worst Case: $O(n^2)$
- Pivot is always the smallest or largest element (e.g., an already sorted array).
- One partition has $n-1$ elements, the other $0$.
- Recurrence: $T(n) = T(n-1) + O(n)$
- Solution: $T(n) = O(n^2)$
| Case | Complexity |
|---|---|
| Best | $O(n \log n)$ |
| Average | $O(n \log n)$ |
| Worst | $O(n^2)$ |
| Space | $O(\log n)$ avg |
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.