Given an array of 0's and 1's alone in decreasing order, find the number of 1's in the array.
Implementation:
Implementation:
#include <stdio.h> #include <stdlib.h> /* Globally declare variable n, will be visible to all the functions of the program */ int n; /* Function binary search to find the number of ones in the sorted list */ int binarysearch(int *a,int l,int r) { int mid; /* Check if the list contains no 1's, if so return count as zero */ if(*(a+0)==0) return 0; /* Check if the last element of the array is 1, then the entire size of the array is count of ones */ if(*(a+n-1)==1) return n; /* Perform recursive modified binary search calculating middle index */ mid=(l+r)/2; /* Find the index of the last occurence of 1 in the list */ if(*(a+mid)==1 && *(a+mid+1)==0) return mid+1; else if(*(a+mid)==1 && *(a+mid+1)==1) return binarysearch(a,mid+1,r); else return binarysearch(a,l,mid-1); } int main(void) { /* Input array */ int a[]={1,1,1,0,0,0}; /* Calculate the size of the array */ n=sizeof(a)/sizeof(a[0]); /* Print the count of number of ones in the array */ printf("count of ones is %d",binarysearch(a,0,n-1)); return 0; }