fork(12) download
  1. #include <stdio.h>
  2.  
  3. // Function to find number of 1's in a sorted binary array
  4. int count(int arr[], int n)
  5. {
  6. // if last element of the array is 0, no ones can
  7. // be present in it since it is sorted
  8. if (arr[n - 1] == 0) {
  9. return 0;
  10. }
  11.  
  12. // if first element of the array is 1, all its elements
  13. // are ones only since it is sorted
  14. if (arr[0]) {
  15. return n;
  16. }
  17.  
  18. // divide array into left and right sub-array and recurse
  19. return count(arr, n/2) + count(arr + n/2, n - n/2);
  20. }
  21.  
  22. // main function
  23. int main(void)
  24. {
  25. int arr[] = { 0, 0, 0, 0, 1, 1, 1 };
  26. int n = sizeof(arr) / sizeof(arr[0]);
  27.  
  28. printf("Total number of 1's present are %d", count(arr, n));
  29.  
  30. return 0;
  31. }
Success #stdin #stdout 0s 9432KB
stdin
Standard input is empty
stdout
Total number of 1's present are 3