8-5 Average sorting

Suppose that, instead of sorting an array, we just require that the elements increase on average. More precisely, we call an nn-element array AA k-sorted if, for all i=1,2,,nki = 1, 2, \ldots, n - k, the following holds:

j=ii+k1A[j]kj=i+1i+kA[j]k.\frac{\sum_{j = i}^{i + k - 1} A[j]}{k} \le \frac{\sum_{j = i + 1}^{i + k} A[j]}{k}.

a. What does it mean for an array to be 11-sorted?

b. Give a permutation of the numbers 1,2,,101, 2, \ldots, 10 that is 22-sorted, but not sorted.

c. Prove that an nn-element array is kk-sorted if and only if A[i]A[i+k]A[i] \le A[i + k] for all i=1,2,,nki = 1, 2, \ldots, n - k.

d. Give an algorithm that kk-sorts an nn-element array in O(nlg(n/k))O(n\lg (n / k)) time.

We can also show a lower bound on the time to produce a kk-sorted array, when kk is a constant.

e. Show that we can sort a kk-sorted array of length nn in O(nlgk)O(n\lg k) time. (Hint:\textit{Hint:} Use the solution to Exercise 6.5-9.)

f. Show that when kk is a constant, kk-sorting an nn-element array requires Ω(nlgn)\Omega(n\lg n) time. (Hint:\textit{Hint:} Use the solution to the previous part along with the lower bound on comparison sorts.)

a. Ordinary sorting

b. 2,1,4,3,6,5,8,7,10,92, 1, 4, 3, 6, 5, 8, 7, 10, 9.

c.

j=ii+k1A[j]kj=i+1i+kA[j]kj=ii+k1A[j]j=i+1i+kA[j]A[i]A[i+k]. \begin{aligned} \frac{\sum_{j = i}^{i + k - 1} A[j]}{k} & \le \frac{\sum_{j = i + 1}^{i + k}A[j]}{k} \\ \sum_{j = i}^{i + k- 1 } A[j] & \le \sum_{j = i + 1}^{i + k} A[j] \\ A[i] & \le A[i + k]. \end{aligned}

d. Shell-Sort, i.e., We split the nn-element array into kk part. For each part, we use Insertion-Sort (or Quicksort) to sort in O(n/klg(n/k))O(n / k \lg(n / k)) time. Therefore, the total running time is kO(n/klg(n/k))=O(nlg(n/k))k \cdot O(n / k \lg(n / k)) = O(n\lg(n / k)).

e. Using a heap, we can sort a kk-sorted array of length nn in O(nlgk)O(n\lg k) time. (The height of the heap is lgk\lg k, the solution to Exercise 6.5-9.)

f. The lower bound of sorting each part is Ω(n/klg(n/k))\Omega(n / k\lg(n / k)), so the total lower bound is Θ(nlg(n/k))\Theta(n\lg (n/k)). Since kk is a constant, therefore Θ(nlg(n/k))=Ω(nlgn)\Theta(n\lg(n / k)) = \Omega(n\lg n).