7.1-1 refer to the method in figure 7-1 to illustrate the partition operation on the array a=<13,19,9,5,12,8,7,4,21,2,6,11>.
A: Golang implementation:
// Partition 分解重排步骤func Partition(a QuickSortInterface, p int, r int) int { x := a.Get(r) i := p - 1 for j := p; j < r; j++ { if a.Get(j) < x { i++ a.Swap(i, j) } } a.Swap(i+1, r) return i + 1}
The result is:
[9 5 8 7 4 2 6 11 21 13 19 12]
7.1-2 when array a[p: R] All the elements in the same value, what is the Q value returned by partition? Modify the partition so that when the array a[p: R] All elements in the same value, q=[(P+R)/2]
Answer: The value returned by partition is R; Change the fourth line to
if a.Get(j) < x && j%2 == p%2
7.1-3 please briefly demonstrate that the time complexity of partition is O (n) on a subarray of size n
A: In the For loop, for each element of the subarray, a judgment is made that the cost of the operation time outside the loop is constant, so the complexity is O (n).
How does 7.1-4 modify the quicksort so that it can be sorted in non-incrementing order?
Answer: will be a. Get (j) < x condition changed to a. Get (j) > x.