Asked By : Smart Home
Answered By : Itay Hazan
- Compute $Y_1 = mathcal A (X,n)$. Intuitively, $Y_1 [i]$ contains the number of elements in $X$ that are larger than $X[i]$ and “to its right”.
- Generate the array $R = reverse(X)$, i.e. $R[i] = X[n-i]$ for every $i in [n]$.
- Compute $Y_2 = mathcal A (R,n)$. Intuitively, $Y_1 [i]$ contains the number of elements in $R$ that are larger than $R[i]$ and “to its right”, i.e. the number of elements in $X$ that are larger than $X[n-i]$ and “to its left”.
- Generate a new array $I$ that satisfies: $I[i] = Y_1 [i] + Y_2 [n-i] + 1$ for every $iin [n]$. Intuitively, $I[i]$ is the number of elements that are greater than or equal to $X[i]$ in $X$, i.e. the position in which we should put $X[i]$ in the output array.
- Generate the output array: $O[I[i]] = X[i]$ for every $iin [n]$.
The correctness of the algorithm is immediate. As to its complexity, steps 2,4 and 5 take $O(n)$, and steps 1 and 3 take $o(n log n)$. We were therefore able to sort an array in time $o(nlog n)$, which contradicts the known lower bound of $Omega(nlog n)$ for sorting. An algorithm that runs in time $O(nlog n)$:
- Create an empty balanced binary search tree, e.g. an AVL tree or a red-black tree. Each node in the tree will hold additional information of the number of elements in its subtree. This data can be easily maintained in insertions and deletions.
- Go over the input array from right to left, and for each element $X[i]$:
- Insert $X[i]$ to the tree. While doing so, use the additional information in the nodes in order to compute the number of elements in the tree that are larger than $X[i]$, and save the result in $O[i]$.
- Finally, update the additional information along the insertion path in the tree and re-balance the tree.
- Output the array $O$.
The correctness of the algorithm follows from the fact that we insert the elements to the tree from the rightmost element in the array to the leftmost element in the array. Therefore, when inserting the element in the $i$’th position to the tree, the elements that are currently in the tree are all of the elements to its right, and hence the computation in step 2 returns the number of elements in the array that are larger than the $i$’th element and to its right, as desired. As for the complexity of the algorithm, since the height of the tree is $O(log n)$, the algorithm runs in time $O(n log n)$. Hope that helps 🙂
Best Answer from StackOverflow
Question Source : http://cs.stackexchange.com/questions/63626 Ask a Question Download Related Notes/Documents