문제

Why use a randomized quick sort, if we already get a random array?

If we receive a random array, and choose the last entry as the pivot every time, isn't that still considered random since we received a random array in which we don't even know where each entry placement they're in.

PSEUDO CODE for Regular Quicksort

QUICKSORT(A,p,r)
if p< r
     q = PARTITION(A,p,r)
     QUICKSORT(A,p,q-1)
     QUICKSORT(A,q+1,r)

PARTITION(A, p, r)
x = A[r]
i = p − 1
for j = p to r − 1 do
     if A[j] ≤ x then
          i = i + 1
          exchange A[i] and A[j]

exchange A[i + 1] and A[r]
return i + 1

PSEUDO CODE for Randomized Quicksort

RandPartition(A, p, r)
     i = Random(p, r)
     exchange A[r] and A[i]
     return PARTITION(A, p, r)

RandQuicksort(A, p, r)
     if p < r then
     q = RandPartition(A, p, r)
     RandQuicksort(A, p, q − 1)
     RandQuicksort(A, q + 1, r)
도움이 되었습니까?

해결책

Yes, if the input is known to be randomized, then the additional randomization serves no purpose. Deterministically choosing the last element as the pivot would be just as good.

The picture's quite different if the input is not know to to be randomized.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top