![]() |
VOOZH | about |
Given an array of N integers with duplicates allowed. All elements are ranked from 1 to N in ascending order if they are distinct. If there are say x repeated elements of a particular value then each element should be assigned a rank equal to the arithmetic mean of x consecutive ranks.
Examples:
Input : 20 30 10
Output : 2.0 3.0 1.0
Input : 10 12 15 12 10 25 12
Output : 1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0
10 is the smallest and there are two 10s so
take the average of two consecutive ranks
1 and 2 i.e. 1.5 . Next smallest element is 12.
Since, two elements are already ranked, the
next rank that can be given is 3. However, there
are three 12's so the rank of 2 is (3+4+5) / 3 = 4.
Next smallest element is 15. There is only one 15
so 15 gets a rank of 6 since 5 elements are ranked.
Next element is 25 and it gets a rank of 7.
Input : 1, 2, 5, 2, 1, 60, 3
Output : 1.5, 3.5, 6.0, 3.5, 1.5, 7.0, 5.0
Method I (Simple):
Consider that there are no repeated elements. In such a case the rank of each element is simply 1 + the count of smaller elements in the array. Now if the array were to contain repeated elements then modify the ranks by considering the no of equal elements too. If there are exactly r elements which are less than e and s elements which are equal to e, then e gets the rank given by
(r + r+1 + r+2 ... r+s-1)/s
[Separating all r's and applying
natural number sum formula]
= (r*s + s*(s-1)/2)/s
= r + 0.5*(s-1)
Algorithm:
function rankify(A)
N = length of A
R is the array for storing ranks
for i in 0..N-1
r = 1, s = 1
for j in 0..N-1
if j != i and A[j] < A[i]
r += 1
if j != i and A[j] = A[i]
s += 1
// Assign Rank to A[i]
R[i] = r + 0.5*(s-1)
return R
Implementation of the method is given below
1 2 5 2 1 25 2 1.5 4 6 4 1.5 7 4
Time Complexity: O(N*N),
Auxiliary Space: O(N)
Method II (Efficient)
In this method, create another array (T) of tuples. The first element of the tuple stores the value while the second element refers to the index of the value in the array. Then, sort T in ascending order using the first value of each tuple. Once sorted it is guaranteed that equal elements become adjacent. Then simply walk down T, find the no of adjacent elements and set ranks for each of these elements. Use the second member of each tuple to determine the indices of the values.
Algorithm
function rankify_improved(A)
N = Length of A
T = Array of tuples (i,j),
where i = A[i] and j = i
R = Array for storing ranks
Sort T in ascending order
according to i
for j in 0...N-1
k = j
// Find adjacent elements
while A[k] == A[k+1]
k += 1
// No of adjacent elements
n = k - j + 1
// Modify rank for each
// adjacent element
for j in 0..n-1
// Get the index of the
// jth adjacent element
index = T[i+j][1]
R[index] = r + (n-1)*0.5
// Skip n ranks
r += n
// Skip n indices
j += n
return R
The code implementation of the method is given below
1 2 5 2 1 25 2 1.5 4 6 4 1.5 7 4
Time Complexity: O(N Log N).
Auxiliary Space: O(N)