Figure 6 presents the code for sorting an integer array. Assume that we make a call to the xsort(…) function with
void swap(int &v1, int &v2) { int t; t = v2; v2 = v1; v1 = t; }
void partition(int data[], int size, int pivot_v, int& low, int& high) {
low = -1;
high = size;
for (int i = 0; i < high;) {
if (data[i] > pivot_v) {
swap(data[i], data[++low]);
++i;
} else if (data[i] < pivot_v) {
swap(data[i], data[--high]);
} else {
++i;
}
}
}
void xsort(int data[], int size)
{
int pivot, low, high;
if (size <= 1)
return;
pivot = size/2;
partition(data, size, data[pivot], low, high);
xsort(data, low+1);
xsort(data+high, size - high);
}
int data[] = {2,0,1,3,2,4,1,0,0,1}; int size = 10;
(1) After the call to xsort returns, the content of the data[] array will be ____ (list all 10 elements sequentially).
(2) How many times will the function partition be invoked? ____ times.
(3) The worst-case time complexity of the xsort function for an input array data[] with size elements is ____.
partition:大於 pivot 的往前丟、小於 pivot 的往後丟、等於 pivot 的留在中間 → 大到小的 3-way quicksort(Dutch national flag)
\([0,\text{low}]\) 是大於 pivot 的,\([\text{high},\text{size})\) 是小於 pivot 的,中間是等於 pivot;遞迴只處理兩邊
第 1 次 pivot 取到最大值 4,左邊 size 0 不用遞迴,右邊剩 9 個;之後的遞迴只有 size 3 的兩塊 \([3,2,2]\)、\([0,0,0]\) 還要 partition(size ≤ 1 的直接 return)
(1) 4 3 2 2 1 1 1 0 0 0 (2) 4 次
(3) 每次 pivot 取到極端值(例如已排序的陣列,pivot=size/2 是中位數看不出來,但 pivot 總是最大值或最小值的輸入存在),\(T(n)=T(n-1)+O(n)\)
\(O(n^2)\)