7.1-1
藍色部分代表不大於pivot,紅色部分表示大於pivot
13 19 9 5 12 8 7 4 21 2 6 11
13 19 9 5 12 8 7 4 21 2 6 11
13 19 9 5 12 8 7 4 21 2 6 11
9 13 19 5 12 8 7 4 21 2 6 11
9 5 13 19 12 8 7 4 21 2 6 11
9 5 13 19 12 8 7 4 21 2 6 11
9 5 8 13 19 12 7 4 21 2 6 11
9 5 8 7 13 19 12 4 21 2 6 11
9 5 8 7 4 13 19 12 21 2 6 11
9 5 8 7 4 13 19 12 21 2 6 11
9 5 8 7 4 2 13 19 12 21 6 11
9 5 8 7 4 2 6 13 19 12 21 11
9 5 8 7 4 2 6 11 13 19 12 21
7.1-2
當所有的元素都相同的時候q=r,這是因為該算法結束后有$a_q \lt a_i, \ (q \lt i \le r)$,所以沒有任何元素會在A[q]之后。
將算法變成交替地將等於pivot的元素放到大小兩個集合中,這樣就能使得$q=\lfloor (p+r)/2 \rfloor$。
Partition(A, p, r) x = A[r] f = 0 i = p - 1 for j = p to r - 1 if x > A[i] or (f > 0 and x == A[i]) i = i + 1 exchange A[i] with A[j] f = f xor 1 exchange A[i + 1] with A[r] return i + 1
7.1-3
由於j從p變為r-1,而循環內的操作運行時間都與輸入規模無關為O(1),循環共進行r-p次,所以總的時間復雜度為O(r-p)=O(n)。
7.1-4
只要把比pivot小的元素放到后邊,把比pivot大的元素放在前邊即可。
Partition(A, p, r) x = A[r] i = p - 1 for j = 1 to r - 1 if A[i] > x i = i + 1 exchange A[i] with A[j] exchange A[i + 1] with A[r] return i + 1
待續。。。