# H-Index II in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of citations (The citations are non-negative integers) of a researcher. These numbers are sorted in non-decreasing order. We have to define a function to compute the researcher's h-index. According to the definition of h-index: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."

So if the input is like citations = [0,1,4,5,6], then the output will be 3, as it indicates that the researcher has five papers, they have got 0, 1, 4, 5, 6 citations respectively. Since the researcher has 3 papers with at least 4 citations each and the remaining two paper with no more than 4 citations each, then the h-index is 3.

To solve this, we will follow these steps −

• ans := 0, low := 0, n := size of the array, high := n – 1

• if size of the array = 0, then return 0

• while low <= high −

• mid := low + (high - low)/2

• if A[mid] = size of array – mid, then return A[mid]

• otherwise when A[mid] > n – mid, then high := mid – 1

• otherwise low := mid + 1

• return n – high – 1

## Example(C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int hIndex(vector<int>& A) {
int ans = 0;
int low = 0;
int n = A.size();
int high = n - 1;
if(A.size() == 0) return 0;
while(low <= high){
int mid = low + (high - low) / 2;
if(A[mid] == A.size() - mid){
return A[mid];
}
else if(A[mid] > (n - mid)){
high = mid - 1;
}
else low = mid + 1;
}
return n - (high + 1);
}
};
main(){
Solution ob;
vector<int> v = {0,1,4,5,7};
cout << (ob.hIndex(v));
}

## Input

[0,1,4,5,6]

## Output

3
Published on 02-May-2020 11:00:12