Count 1’s in a sorted binary array in C++


In this tutorial, we will be discussing a program to find the 1’s in a sorted binary array.

For this we will be provided with an array containing only 1 and 0. Our task is to count the number of 1’s present in the array.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//returning the count of 1
int countOnes(bool arr[], int low, int high){
   if (high >= low){
      int mid = low + (high - low)/2;
      if ( (mid == high || arr[mid+1] == 0) && (arr[mid] == 1))
         return mid+1;
      if (arr[mid] == 1)
         return countOnes(arr, (mid + 1), high);
      return countOnes(arr, low, (mid -1));
   }
   return 0;
}
int main(){
   bool arr[] = {1, 1, 1, 1, 0, 0, 0};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Count of 1's in given array is " << countOnes(arr, 0, n-1);
   return 0;
}

Output

Count of 1's in given array is 4

Updated on: 05-Feb-2020

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements