Find the only missing number in a sorted array | JavaScript program to find the only missing element . ; If this is the first element which is not index + 1 , then missing element is mid + 1 ; if this is not the first missing element search in left side ; if it follows index + 1 property then search in right side ; if no element is missing ; Driver code
function findmissing ( ar , N ) { var l = 0 , r = N - 1 ; while ( l <= r ) { var mid = parseInt ( ( l + r ) / 2 ) ; if ( ar [ mid ] != mid + 1 && ar [ mid - 1 ] == mid ) return mid + 1 ; if ( ar [ mid ] != mid + 1 ) r = mid - 1 ; else l = mid + 1 ; } return - 1 ; } var arr = [ 1 , 2 , 3 , 4 , 5 , 7 , 8 ] ; var N = arr . length ; document . write ( findmissing ( arr , N ) ) ;