
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements