Reputation: 33
A question I got on recent interview:
Consider an array with n elements which is divided into three parts:
A[1] .....................................................A[n] part1(m1)..........part2(m2)......... part3(m3)
Then quick sort is run on it three times as follows:
QuickSort(A[m1+1.....n]) QuickSort(A[1.....m1+m2]) QuickSort(A[m1+1.....n])
Under what condition is the array is sorted?
a) m1>m2 b) m1<m2 c) m1>=m2 d) m1=m2=m3
My answer was m1>m2
but now I am in doubt whether m1>=m2
is also correct. Is this right?
Upvotes: 3
Views: 265
Reputation: 6251
Consider the case where
A = 3 3 3 2 2 1
m1 = 3, m2 = 2, m3 = 1, n = 6
If we sort using quicksort (qs) in the ways given we get:
qs(A[3+1..6]) -> 3 3 3 [1 2 2]
qs(A[1..2+3]) -> [1 2 3 3 3] 2
qs(A[3+1..6]) -> 1 2 3 [2 3 3]
The final result: 1 2 3 2 3 3 is not sorted.
In this case, the result is not sorted because m2 was smaller than m1 so the minimum m1 values could not be carried over from part 3 to part 1 using part 2 as a (sort of) buffer. So we must have m1 <= m2.
Upvotes: 1
Reputation: 18556
I claim that m1 <= m2
is necessary and sufficient.
If it is the case, after the first we can be sure that m2
smallest numbers from the m1 + 1 ... n
part are located inside the 1 ... m1 + m2
prefix. m2
>= m1
, thus m1
smallest numbers are inside the 1 ... m1 + m2
prefix. It means that after the second run they will be on their correct positions. It does not matter what's going on in the m1 + 1 ... n
part because it will be fixed during the last run anyway.
If it is not the case, it is easy to build a counter example: {3, 3, 1, 2, 2}, m1 = m3 = 2, m2 = 1.
It means that both: b) and d) are correct.
Upvotes: 2
Reputation: 9570
The last run won't touch part1
, so part1
must contain m1
smallest items of the array after the second run. If some of them are initially in part1
that's OK; if they are in part2
the second run will bring them to the right place; however those who are in part3
must be shifted to part2
first. If the array is initially in reverse order, then m1>=m2>=m3
must be satisfied to bring m3
least items from the right end of the array to the left one. Similary m1<=m2<=m3
seems necessary to guarantee m1
largest items from part1
will be shifted to part3
.
Final answer: d.
Upvotes: 0