What you need is an ‘order-statistics tree’. It is essentially an augmented (binary search) tree that supports the additional operation rank(x)
which gives you the number of elements with less or equal key as element x
. Chapter 14 in Cormen, Leiserson, Rivest, Stein; “Introduction to Algorithms” should give you the algorithmic background.
There is also some implementation on the web.