Suppose that you’re given an array A of n distinct elements drawn from some totally-ordered set. For example, you might be given
137 13 7 42 38
The goal is to produce for this array of elements a matching array B such that B[i] is the number of elements in the original array that are smaller than A[i]. For example, in the above array, we’d want to produce
A = 137 13 7 42 38
B = 4 1 0 3 2
Since 137 is bigger than four other elements (13, 7, 42, 38), 13 is only bigger than one of the elements (7), 7 is bigger than no other elements, etc.
In the most general case, where the elements in the array are arbitrary objects that can only be compared, any solution to this problem must run in Ω(n lg n) in the worst case because once we have this table, we can sort the array in O(n) time by making a new array of n elements, then putting each element in the position specified in the table. However, what I don’t know is how fast we can construct this table when the elements are not arbitrary values.
My question is this: suppose that you’re given an array of n distinct integer values and want to construct a table of order statistics for that array. What is the most efficient algorithm for doing so? If it helps, you can assume the integers are positive and that the largest of them has value U.
Currently, the best I have is an O(n lg n) solution that works by making a copy of the array, sort it, then for each integer in the original array, doing a binary search to find its position in the new array. This is a fine solution, but I was really hoping that there would be some better way of doing this.
Step 1: sort the original array indexes.
Step 2: for every
I'[i] = jassignB[j] = i.