Rightmost position of insertion

Write an efficient function

    int rightmost(double x, const vector<double>& v);

that returns the rightmost position where xx could be inserted in the sorted vector vv (by adding one position at the end of vv and moving the necessary elements one position to the right) so that vv would remain sorted.

For instance, assume that xx is 23. If vv is [15,15,20,30,40,40][15, 15, 20, 30, 40, 40], then we must insert xx at the position 3 (between 20 and 30), and the resulting vv would be [15,15,20,23,30,40,40][15, 15, 20, 23, 30, 40, 40]. If vv is [17,23,23,35,42,42][17, 23, 23, 35, 42, 42], then we could insert xx at the positions 1, 2 or 3, so your function must return 3. If vv is [3,5,7,9][3, 5, 7, 9], xx should be inserted at the position just to the right of the end of the vector, that is, 4. As a final example, if vv is [23,23][23, 23], xx should be inserted at 2.

Precondition

The vector vv is sorted in nondecreasing order.

Observations

Problem information

Author: Unknown
Translator: Salvador Roura

Generation: 2026-03-10T20:03:56.512Z

© Jutge.org, 2006–2026.
https://jutge.org