Since the input array is already sorted, you can use binary search to improve performance. This improves the run time to O (log n).
An algorithm that uses binary search:
Algorithm : zeroCount(A)
Input : sorted array A containing 0s and 1s
Output : total number of 0s in A
if A[0]=1 then
return 0;
len <— A.length
if A[len-1]=0 then
return len
return count(A,0,length)
Algorithm : count(A,lower,upper)
Input : sorted array A , integers lower and upper
Output : total number of 0s in A
mid <— (lower+upper) / 2
if A[mid] != A[mid-1] then
return mid
if A[mid] != A[mid+1] then
return mid+1
if A[mid] = 1 then
return count(A,lower,mid-1)
if A[mid] = 0 then
return count(A,mid+1,upper)
Java implementation:
public int zeroCount(int[] a) {
if (a[0] == 1)
return 0;
int length = a.length;
if (a[length - 1] == 0)
return length;
return count(a, 0, length);
}
public int count(int[] a, int lower, int upper) {
int mid = (lower + upper) / 2;
if (a[mid] != a[mid - 1])
return mid;
if (a[mid] != a[mid + 1])
return mid + 1;
if (a[mid] == 1) {
return count(a, lower, mid - 1);
} else if (a[mid] == 0) {
return count(a, mid + 1, upper);
}
return 0;
}
source
share