What value of \(q\) does \(\textsc{Partition}\) return when all elements in the array \(A[p..r]\) have the same value? Modify \(\textsc{Partition}\) so that \(q = \lfloor (p+r)/2 \rfloor\) when all elements in the array \(A[p..r]\) have the same value.
Here’s the original algorithm for \(\textsc{Partition}\):
When all elements have the same value, the \(\textsc{Partition}\) procedure behaves in a specific way. Since the pivot \(x = A[r]\) equals all other elements, every comparison \(A[j] \leq x\) in line 4 evaluates to true. This means the algorithm swaps every element with itself (when \(i\) catches up to \(j\)), incrementing \(i\) each time.
Starting with \(i = p - 1\) and \(j\) ranging from \(p\) to \(r - 1\), after the loop completes, we have \(i = r - 1\). The final swap in line 7 exchanges \(A[r]\) with \(A[r - 1 + 1] = A[r]\), and the procedure returns \(q = r\).
Therefore, when all elements are equal, \(\textsc{Partition}\) returns \(q = r\), creating a highly unbalanced split: one subarray with \(n - 1\) elements and one empty subarray. This is the worst-case scenario for quicksort.
To achieve \(q = \lfloor (p + r)/2 \rfloor\) when all elements are equal, we need to detect number of elements that are equal to pivot and adjust the final partition index to the left. Here’s a modified version:
The key insight is counting how many elements equal the pivot. If equal-count == r - p, then all \(r - p\) elements from \(p\) to \(r - 1\) equal the pivot, which means (including the pivot at \(r\)) all elements are identical. In this case, we return the middle index.