Count 1 's in a sorted binary array | package whatever ; Returns counts of 1 's in arr[low..high]. The array is  assumed to be sorted in non-increasing order  ; get the middle index ; else recur for left side ; If element is not last 1 , recur for right side ; check if the element at middle index is last 1 ; Driver code
import java . io . * ; class GFG { static int countOnes ( int arr [ ] , int n ) { int ans ; int low = 0 , high = n - 1 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( arr [ mid ] < 1 ) high = mid - 1 ; else if ( arr [ mid ] > 1 ) low = mid + 1 ; else { if ( mid == n - 1 arr [ mid + 1 ] != 1 ) return mid + 1 ; else low = mid + 1 ; } } return 0 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 1 , 0 , 0 , 0 } ; int n = arr . length ; System . out . println ( " Count ▁ of ▁ 1 ' s ▁ in ▁ given ▁ array ▁ is ▁ " + countOnes ( arr , n ) ) ; } }