7-2 Quicksort with equal element values

The analysis of the expected running time of randomized quicksort in section 7.4.2 assumes that all element values are distinct. In this problem. we examine what happens when they are not.

a. Suppose that all element values are equal. What would be randomized quick-sort's running time in this case?

b. The PARTITION\text{PARTITION} procedure returns an index qq such that each element of A[p..q1]A[p..q - 1] is less than or equal to A[q]A[q] and each element of A[q+1..r]A[q + 1..r] is greater than A[q]A[q]. Modify the PARTITION\text{PARTITION} procedure to produce a procedure PARTITION(A,p,r)\text{PARTITION}'(A, p, r) which permutes the elements of A[p..r]A[p..r] and returns two indices qq and tt where pqtrp \le q \le t \le r, such that

  • all elements of A[q..t]A[q..t] are equal,
  • each element of A[p..q1]A[p..q - 1] is less than A[q]A[q], and
  • each element of A[t+1..r]A[t + 1..r] is greater than A[q]A[q].

Like PARTITION\text{PARTITION}, your PARTITION\text{PARTITION}' procedure should take Θ(rp)\Theta(r - p) time.

c. Modify the RANDOMIZED-QUICKSORT\text{RANDOMIZED-QUICKSORT} procedure to call PARTITION\text{PARTITION}', and name the new procedure RANDOMIZED-QUICKSORT\text{RANDOMIZED-QUICKSORT}'. Then modify the QUICKSORT\text{QUICKSORT} procedure to produce a procedure QUICKSORT(p,r)\text{QUICKSORT}'(p, r) that calls RANDOMIZED-PARTITION\text{RANDOMIZED-PARTITION}' and recurses only on partitions of elements not know to be equal to each other.

d. Using QUICKSORT\text{QUICKSORT}', how would you adjust the analysis of section 7.4.2 to avoid the assumption that all elements are distinct?

a. Since all elements are equal, RANDOMIZED-QUICKSORT\text{RANDOMIZED-QUICKSORT} always returns q=rq = r. We have recurrence T(n)=T(n1)+Θ(n)=Θ(n2)T(n) = T(n - 1) + \Theta(n) = \Theta(n^2).

b.

PARTITION'(A, p, r)
    x = A[p]
    low = p
    high = p
    for j = p + 1 to r
        if A[j] < x
            y = A[j]
            A[j] = A[high + 1]
            A[high + 1] = A[low]
            A[low] = y
            low = low + 1
            high = high + 1
        else if A[j] == x
            exchange A[high + 1] with A[j]
            high = high + 1
    return (low, high)

c.

QUICKSORT'(A, p, r)
    if p < r
        (low, high) = RANDOMIZED-PARTITION'(A, p, r)
        QUICKSORT'(A, p, low - 1)
        QUICKSORT'(A, high + 1, r)

d. Since we don't recurse on elements equal to the pivot, the subproblem sizes with QUICKSORT\text{QUICKSORT}' are no larger than the subproblem sizes with QUICKSORT\text{QUICKSORT} when all elements are distinct.