Find rows of elements in an array efficiently?

How can one efficiently find the rank of each element of the array by averaging in the case of relations? For example:

float[] rank(T)(T[] input) {
    // Implementation
}

auto foo = rank([3,6,4,2,2]);  // foo == [3, 5, 4, 1.5, 1.5]

The only way I can do this is to allocate 3 arrays:

  • A duplicate of the input array, because it must be sorted, and we do not own it.
  • An array to track the sort order of the input array.
  • Array of ranks to return.

Does anyone know how to do this in O (N log N) time and O (1) auxiliary space (which means that the only array we need to allocate is the one we are going to return) or at least get rid one of the three arrays above?

+3
source share
7

, ( R), 0..n-1, "" ( I), [R [k ]] [R [j]] R [k] R [j], R ( I, ).

, quicksort, heapsort ( bubblesort, ).

- .

+4

, foo. foo O (n log n) heapsort. foo O (log n), ranks .

2 3.

+2

, , O (N log N) O (1).

( ) , . , .

c - is counting result,
C - is cumulative counting
C[i] = c[i] + c[i-1] + c[i-2] + ... + c[0]
result[i] = 1 / c[in[i]] + C[in[i]-1]
0

? , heapsort.

0

, florin ( ) .

Ruby:

arr = [5,1,0,3,2,4]
ranks = (0..arr.length-1).to_a.sort_by{ |x| arr[x] }
# ranks => [2, 1, 4, 3, 5, 0]

Python:

arr = [5,1,0,3,2,4]
ranks = range(len(arr))
ranks.sort(key=lambda x:arr[x])
# ranks => [2, 1, 4, 3, 5, 0]

, 0 2, 1 1, 2 4 .. (, , .)

0

BST. , , node, BST.

0
source

I used this for quick and dirty in python:

def rank(X):
    B = X[:]
    B.sort()
    return [ float(B.index(x)+1) for x in X]

def rank(X):
    B = X[:]
    B = list(set(B))
    B.sort()
    return [ float(B.index(x)+1) for x in X]

The first example will work if you do not have duplicates in the original list. This can be done better, but I played with some hacks and went out with it. The second will work if you have duplicates.

0
source

Source: https://habr.com/ru/post/1721886/


All Articles