ronith
6/14/2018 - 6:11 AM

Count 1’s in a sorted binary array

// https://www.geeksforgeeks.org/count-1s-sorted-binary-array/
#include <iostream>
using namespace std;

int func(int a[], int l, int r){
    if (l<=r){
        int m=(l+r)/2;

        if ( (m==r || a[m+1] == 0) && a[m] == 1)
            return m;
        if (a[m] == 1)
            return func(a,m+1,r);
        return func(a,l,m-1);
    }
    return 0;
}

int main(){
    int n;
    cin >> n;
    int a[n];
    for (int i=0; i<n; i++)
        cin >> a[i];

    int j=func(a,0,n-1);
    cout << j+1;
}