/
FindTheNumberOfZeros.cpp
53 lines (44 loc) · 1.54 KB
/
FindTheNumberOfZeros.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Find the number of zeroes
Given an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array.
ALgo:
Since the input array is sorted, we can use Binary Search to find the first occurrence of 0. Once we have index of first element,
we can return count as n – index of first zero.
Time Complexity: O(Logn) where n is number of elements in arr[].
*/
#include <iostream>
/* if 0 is present in arr[] then returns the index of FIRST occurrence
of 0 in arr[low..high], otherwise returns -1 */
int firstZero(int arr[], int low, int high)
{
if (high >= low)
{
// Check if mid element is first 0
int mid = low + (high - low)/2;
if (( mid == 0 || arr[mid-1] == 1) && arr[mid] == 0)
return mid;
if (arr[mid] == 1) // If mid element is not 0
return firstZero(arr, (mid + 1), high);
else // If mid element is 0, but not first 0
return firstZero(arr, low, (mid -1));
}
return -1;
}
// A wrapper over recursive function firstZero()
int countOnes(int arr[], int n)
{
// Find index of first zero in given array
int first = firstZero(arr, 0, n-1);
// If 0 is not present at all, return 0
if (first == -1)
return 0;
return (n - first);
}
/* Driver program to check above functions */
int main()
{
int arr[] = {1, 1, 0, 0, 0, 0, 0, 0};
int n = sizeof(arr)/sizeof(arr[0]);
std::cout<< "Count of zeroes is "<<countOnes(arr, n)<<std::endl;
return 0;
}