comparing rank of a number from a reverse sorted array

Viewed 58

i have an array like this array={100,50,40,20,10}, currently rank of 100 is 1, rank of 50 is 2 and so on. now i am comparing rank of point 25, then new array leader board will be {100,50,40,25,20,10} and 25 has rank 4. similarly, if point 120 was to be compared to the original array {100,50,40,20,10}, new array leaderboard will be {120,100,50,40,20,10} rank of 120 is 1 now. the original question is this. since the array is sorted and if too large and have to call such query a number of times I want to do it recursively but each time I get stuck. my current code to do such operation is;

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int find_rank_pos(vector<int>&array,int val){
    int mid=array.size()/2;
    if(array[mid]<=val){
        int pos=1;
        while(array[pos-1]>val && pos<=mid){
            pos++;
    }
    return pos;
    }
    else{
    int pos=mid+2;
    while(array[pos-1]>val && pos<=array.size()){
        pos++;
    }
    return pos;
    }
}
int main(){
    vector<int>ranked={100,100,50,40,40,20,10};
    vector<int>::iterator ip;
    ip =unique(ranked.begin(), ranked.end());
    ranked.resize(std::distance(ranked.begin(), ip));
    vector<int>player={5,25,50,120};
    for(auto x:player){
        cout<<find_rank_pos(ranked,x)<<endl;
    }
}

please help me to optimise my algorithm. kindly looking for the help.

0 Answers
Related