Count 1 's in a sorted binary array | 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
function countOnes ( arr , n ) { let ans ; let low = 0 , high = n - 1 ; while ( low <= high ) { let mid = Math . floor ( ( 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 ; } } } let arr = [ 1 , 1 , 1 , 1 , 0 , 0 , 0 ] ; let n = arr . length ; document . write ( " " + countOnes ( arr , n ) ) ;